fix(collaboration-graph-v2): moved graph generation to background task

This commit is contained in:
Mats Paul Tončik
2026-07-25 12:10:41 +02:00
parent e6eabf08c9
commit 424649ecdc
18 changed files with 120337 additions and 211 deletions
@@ -0,0 +1,117 @@
import datetime
import logging
from datetime import timedelta
from inse.authors.v2.model import (
CollaborationGraph,
CollaborationGraphJob,
CollaborationGraphStatus,
)
from sqlmodel import Session, select
logger = logging.getLogger(__name__)
JOB_RETENTION = timedelta(hours=1)
def create_collaboration_graph_job(session: Session, graph_id: str) -> None:
"""Creates a new collaboration graph job in the database.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to create a job.
"""
existing = session.get(CollaborationGraphJob, graph_id)
if existing:
logger.info(f"Job for graph_id {graph_id} already exists.")
return
job = CollaborationGraphJob(
graph_id=graph_id, status=CollaborationGraphStatus.PENDING
)
session.add(job)
session.commit()
def get_collaboration_graph_job(
session: Session, graph_id: str
) -> CollaborationGraphJob | None:
"""Retrieves a collaboration graph job from the database by its graph ID.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to retrieve the job.
Returns:
CollaborationGraphJob | None: The collaboration graph job if found, otherwise None.
"""
return session.get(CollaborationGraphJob, graph_id)
def mark_collaboration_graph_job_completed(
session: Session, graph_id: str, result: CollaborationGraph
) -> None:
"""Marks a collaboration graph job as completed and stores the result.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to mark the job as completed.
result (CollaborationGraph): The result of the collaboration graph generation.
"""
job = get_collaboration_graph_job(session, graph_id)
if not job:
logger.warning(
f"No job found for graph_id {graph_id}. Cannot mark as completed."
)
return
job.status = CollaborationGraphStatus.COMPLETED
job.set_result(result)
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
session.add(job)
session.commit()
def mark_collaboration_graph_job_failed(
session: Session, graph_id: str, error_message: str
) -> None:
"""Marks a collaboration graph job as failed and stores the error message.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to mark the job as failed.
error_message (str): The error message describing the failure.
"""
job = get_collaboration_graph_job(session, graph_id)
if not job:
logger.warning(f"No job found for graph_id {graph_id}. Cannot mark as failed.")
return
job.status = CollaborationGraphStatus.FAILED
job.error_message = error_message
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
session.add(job)
session.commit()
def cleanup_old_collaboration_graph_jobs(
session: Session, max_age: timedelta = JOB_RETENTION
) -> int:
"""Cleans up old collaboration graph jobs that are older than the retention period.
Args:
session (Session): The SQLModel session to use for database operations.
max_age (timedelta): The maximum age of jobs to retain.
Returns:
int: The number of stale jobs that were cleaned up.
"""
cutoff_time = datetime.datetime.now(datetime.timezone.utc) - max_age
statement = select(CollaborationGraphJob).where(
CollaborationGraphJob.created_at < cutoff_time
)
stale_jobs = session.exec(statement).all()
count = len(stale_jobs)
for job in stale_jobs:
session.delete(job)
session.commit()
if count:
logger.debug("Cleaned up %d stale collaboration graph jobs", count)
return count
+76 -2
View File
@@ -1,8 +1,11 @@
import json
from datetime import datetime
from enum import StrEnum
from inse.model import Page
from inse.models.openalex.author import Author
from pydantic import BaseModel, Field
from pydantic import BaseModel
from sqlmodel import Field, SQLModel
class AuthorPage(Page[Author]):
@@ -96,5 +99,76 @@ class CollaborationGraph(BaseModel):
authors=list(internal_graph.authors.values()),
institutions=list(internal_graph.institutions.values()),
works=list(internal_graph.works.values()),
edges=internal_graph.edges,
edges=_collapse_edges(internal_graph.edges),
)
def _collapse_edges(edges: list[Edge]) -> list[Edge]:
reduced: dict[frozenset[str], Edge] = {}
for edge in edges:
key = frozenset((edge.source, edge.target))
existing = reduced.get(key)
if existing is None:
reduced[key] = Edge(
source=edge.source,
target=edge.target,
weight=edge.weight,
)
else:
existing.weight += edge.weight
return list(reduced.values())
class CollaborationGraphStatus(StrEnum):
PENDING = "pending"
COMPLETED = "completed"
FAILED = "failed"
class StartCollaborationGraphResponse(BaseModel):
graph_id: str = Field(description="The ID of the collaboration graph.")
class CollaborationGraphStatusResponse(BaseModel):
status: CollaborationGraphStatus = Field(
description="The status of the collaboration graph."
)
result: CollaborationGraph | None = Field(
default=None, description="The collaboration graph result if completed."
)
error_message: str | None = Field(
default=None, description="The error message if the graph generation failed."
)
class CollaborationGraphJob(SQLModel, table=True):
__tablename__ = "collaboration_graph_jobs" # type: ignore
graph_id: str = Field(
primary_key=True,
description="The ID of the collaboration graph generation task.",
)
status: CollaborationGraphStatus = Field(
default=CollaborationGraphStatus.PENDING,
description="The status of the collaboration graph generation task.",
)
result: str | None = Field(
default=None,
description="The JSON-serialized result of the collaboration graph generation task.",
)
error_message: str | None = Field(
default=None,
description="The error message if the collaboration graph generation failed.",
)
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
def get_result(self) -> "CollaborationGraph | None":
if self.result is None:
return None
return CollaborationGraph.model_validate_json(self.result)
def set_result(self, value: BaseModel | None) -> None:
self.result = value.model_dump_json() if value is not None else None
+34 -9
View File
@@ -2,11 +2,13 @@ import logging
from typing import Annotated
import inse.authors.v2.service as authors_service
from fastapi import APIRouter, Path, Query
from fastapi import APIRouter, BackgroundTasks, Path, Query
from inse.authors.v2.model import (
AuthorPage,
CollaborationGraph,
CollaborationGraphStatusResponse,
StartCollaborationGraphResponse,
)
from inse.database import SessionDep
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
@@ -46,15 +48,17 @@ async def autocomplete_authors_for_selector(
return await authors_service.autocomplete_authors_for_selector(query=query)
@router.get(
"/collaboration-graph/{raw_oa_author_id}",
operation_id="getCollaborationGraph",
@router.post(
"/collaboration-graph",
operation_id="startCollaborationGraph",
summary="Returns a collaboration graph for a given author ID.",
)
async def get_collaboration_graph(
def start_collaboration_graph(
session: SessionDep,
background_tasks: BackgroundTasks,
raw_oa_author_id: Annotated[
str,
Path(
Query(
description="The raw OpenAlex author ID for which to retrieve the collaboration graph."
),
],
@@ -94,8 +98,10 @@ async def get_collaboration_graph(
description="A list of institution IDs to filter the works by (optional).",
),
] = None,
) -> CollaborationGraph:
return await authors_service.get_collaboration_graph(
) -> StartCollaborationGraphResponse:
return authors_service.start_collaboration_graph(
session=session,
background_tasks=background_tasks,
raw_oa_author_id=raw_oa_author_id,
year_from=year_from,
year_to=year_to,
@@ -104,3 +110,22 @@ async def get_collaboration_graph(
topic_ids=topic_ids,
institution_ids=institution_ids,
)
@router.get(
"/collaboration-graph/{graph_id}/status",
operation_id="getCollaborationGraphStatus",
summary="Returns the status of a collaboration graph generation task.",
)
def get_collaboration_graph_status(
session: SessionDep,
graph_id: Annotated[
str,
Path(
description="The ID of the collaboration graph generation task.",
),
],
) -> CollaborationGraphStatusResponse:
return authors_service.get_collaboration_graph_status(
session=session, graph_id=graph_id
)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+203 -3
View File
@@ -1,23 +1,29 @@
import logging
import inse.works.v2.service as works_service
from fastapi import BackgroundTasks
from inse.authors.institution_membership_query import (
build_active_institution_membership_query,
)
from inse.authors.v2 import collaboration_graph_jobs
from inse.authors.v2.model import (
AuthorNode,
AuthorPage,
CollaborationGraph,
CollaborationGraphStatus,
CollaborationGraphStatusResponse,
Edge,
InstitutionNode,
InternalCollaborationGraph,
MatchMode,
StartCollaborationGraphResponse,
WorkNode,
)
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.models.openalex.author import Author
from inse.works.v2.model import WorkPageV2
from sqlmodel import Session
logger = logging.getLogger(__name__)
@@ -298,7 +304,34 @@ COLLABORATION_GRAPH_SOURCE_FIELDS = [
]
async def get_collaboration_graph(
def _get_collaboration_graph_cache_key(
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
) -> str:
"""Generates a cache key for the collaboration graph based on the provided parameters.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the cache key.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
Returns:
str: The generated cache key.
"""
return f"collaboration_graph:{raw_oa_author_id}:{year_from}:{year_to}:{min_collaborators}:{max_collaborators}:{':'.join(sorted(topic_ids or []))}:{':'.join(sorted(institution_ids or []))}"
async def _build_collaboration_graph(
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
@@ -331,6 +364,9 @@ async def get_collaboration_graph(
topic_ids=topic_ids,
institution_ids=institution_ids,
)
logger.debug(
f"Searching works for collaboration graph of author {raw_oa_author_id} with query: {query}"
)
work_page: WorkPageV2 = await works_service.search_works(
query=query,
@@ -340,10 +376,16 @@ async def get_collaboration_graph(
sort=[{"publication_year": "desc"}, {"id": "asc"}],
)
return _build_collaboration_graph(page=work_page, raw_oa_author_id=raw_oa_author_id)
logger.debug(
f"Retrieved {len(work_page.elements)} works for collaboration graph of author {raw_oa_author_id} (total: {work_page.total})"
)
return _build_collaboration_graph_from_works(
page=work_page, raw_oa_author_id=raw_oa_author_id
)
def _build_collaboration_graph(
def _build_collaboration_graph_from_works(
page: WorkPageV2, raw_oa_author_id: str
) -> CollaborationGraph:
"""Builds a collaboration graph from a page of works and a raw OpenAlex author ID.
@@ -410,6 +452,164 @@ def _build_collaboration_graph(
return graph
jobs: dict[str, dict] = {}
def start_collaboration_graph(
session: Session,
background_tasks: BackgroundTasks,
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
) -> StartCollaborationGraphResponse:
"""Starts the process of generating a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the collaboration graph.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
Returns:
StartCollaborationGraphResponse: The response containing the cache key for the collaboration graph generation process.
"""
cache_key = _get_collaboration_graph_cache_key(
raw_oa_author_id=raw_oa_author_id,
year_from=year_from,
year_to=year_to,
min_collaborators=min_collaborators,
max_collaborators=max_collaborators,
topic_ids=topic_ids,
institution_ids=institution_ids,
)
logger.debug("Generated cache key for collaboration graph: %s", cache_key)
existing_job = collaboration_graph_jobs.get_collaboration_graph_job(
session, cache_key
)
if existing_job:
logger.debug(
"Collaboration graph job already exists for cache key: %s, status: %s",
cache_key,
existing_job.status,
)
return StartCollaborationGraphResponse(graph_id=cache_key)
collaboration_graph_jobs.create_collaboration_graph_job(session, cache_key)
background_tasks.add_task(
_run_collaboration_graph_job,
session,
cache_key,
raw_oa_author_id,
year_from,
year_to,
min_collaborators,
max_collaborators,
topic_ids,
institution_ids,
)
logger.debug(
"Started background task for collaboration graph job with cache key: %s",
cache_key,
)
return StartCollaborationGraphResponse(graph_id=cache_key)
async def _run_collaboration_graph_job(
session: Session,
cache_key: str,
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
) -> None:
"""Runs the collaboration graph generation job in the background and updates the job status in the jobs dictionary.
Args:
cache_key (str): The cache key for the collaboration graph generation process.
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the collaboration graph.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
"""
try:
result = await _build_collaboration_graph(
raw_oa_author_id=raw_oa_author_id,
year_from=year_from,
year_to=year_to,
min_collaborators=min_collaborators,
max_collaborators=max_collaborators,
topic_ids=topic_ids,
institution_ids=institution_ids,
)
logger.debug(
f"Collaboration graph job completed successfully for cache key: {cache_key}"
)
collaboration_graph_jobs.mark_collaboration_graph_job_completed(
session, cache_key, result
)
logger.debug(
f"Collaboration graph job marked as completed for cache key: {cache_key}"
)
except Exception as e:
logger.exception("Collaboration graph job failed: %s", cache_key)
collaboration_graph_jobs.mark_collaboration_graph_job_failed(
session, cache_key, str(e)
)
logger.debug(
f"Collaboration graph job marked as failed for cache key: {cache_key}, error: {e!s}"
)
def get_collaboration_graph_status(
session: Session,
graph_id: str,
) -> CollaborationGraphStatusResponse:
"""Retrieves the status of a collaboration graph generation process based on the provided graph ID.
Args:
graph_id (str): The ID of the collaboration graph generation process.
Returns:
CollaborationGraphStatusResponse: The response containing the status and result (if completed) of the collaboration graph generation process.
"""
job = collaboration_graph_jobs.get_collaboration_graph_job(session, graph_id)
if not job:
logger.debug("No job found for the provided graph ID: %s", graph_id)
return CollaborationGraphStatusResponse(
status=CollaborationGraphStatus.FAILED,
error_message="No job found for the provided graph ID.",
)
logger.debug(
"Retrieved job status for graph ID: %s, status: %s",
graph_id,
job.status,
)
return CollaborationGraphStatusResponse(
status=job.status,
result=job.get_result()
if job.status == CollaborationGraphStatus.COMPLETED
else None,
error_message=job.error_message,
)
def _prefix_id(raw_oa_id: str) -> str:
"""Prefixes the raw OpenAlex ID with "https://openalex.org/" if it does not already start with that prefix.
+1 -1
View File
@@ -2,7 +2,7 @@ from typing import Annotated
from fastapi import Depends
from sqlalchemy import inspect, text
from sqlmodel import SQLModel, Session, create_engine
from sqlmodel import Session, SQLModel, create_engine
from inse import config
+86 -85
View File
@@ -8,23 +8,24 @@ from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
# Responses whose contents depend on the current account or effective
# organization must never be reused by the browser.
NO_STORE_PATH_PREFIXES = (
"/api/auth/v2",
"/api/accounts",
"/api/bookmarks",
"/api/organizations",
"/api/dashboard",
"/api/rank/rank-author",
"/api/v2/works/classification/",
)
NO_STORE_PATH_FRAGMENTS = (
"/company-connections",
"/primary-category-aggregations",
)
# Responses whose contents depend on the current account or effective
# organization must never be reused by the browser.
NO_STORE_PATH_PREFIXES = (
"/api/auth/v2",
"/api/accounts",
"/api/bookmarks",
"/api/organizations",
"/api/dashboard",
"/api/rank/rank-author",
"/api/v2/works/classification/",
)
NO_STORE_PATH_FRAGMENTS = (
"/company-connections",
"/primary-category-aggregations",
"/collaboration-graph/",
)
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
# trigger side effects), even if it "usually" returns 200.
EXCLUDED_POST_PATHS = (
@@ -41,7 +42,7 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
self.ttl = ttl
self.maxsize = maxsize
# Insertion-ordered so we can evict the oldest entry in O(1) when over capacity.
self.cache: "OrderedDict[str, dict]" = OrderedDict()
self.cache: OrderedDict[str, dict] = OrderedDict()
def _get(self, key: str) -> dict | None:
entry = self.cache.get(key)
@@ -91,61 +92,61 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
return f"{user_id}:{base}"
return base
def _content_type(self, response: Response) -> str | None:
return response.headers.get("content-type")
def _requires_no_store(self, request: Request) -> bool:
path = request.url.path
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
)
def _set_no_store_headers(self, response: Response) -> None:
response.headers["Cache-Control"] = "private, no-store, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
self._append_vary_authorization(response.headers)
@staticmethod
def _append_vary_authorization(headers) -> None:
vary_values = [
value.strip()
for value in headers.get("Vary", "").split(",")
if value.strip()
]
if not any(value.lower() == "authorization" for value in vary_values):
vary_values.append("Authorization")
headers["Vary"] = ", ".join(vary_values)
def _cache_response_headers(
self, request: Request, etag: str, content_type: str | None
) -> dict[str, str]:
cache_control = f"max-age={self.ttl}"
headers = {"ETag": etag, "Cache-Control": cache_control}
if request.headers.get("authorization"):
headers["Cache-Control"] = f"private, {cache_control}"
headers["Vary"] = "Authorization"
if content_type:
headers["Content-Type"] = content_type
return headers
def _is_cacheable_request(self, request: Request) -> bool:
if self._requires_no_store(request):
return False
def _content_type(self, response: Response) -> str | None:
return response.headers.get("content-type")
def _requires_no_store(self, request: Request) -> bool:
path = request.url.path
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
)
def _set_no_store_headers(self, response: Response) -> None:
response.headers["Cache-Control"] = "private, no-store, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
self._append_vary_authorization(response.headers)
@staticmethod
def _append_vary_authorization(headers) -> None:
vary_values = [
value.strip()
for value in headers.get("Vary", "").split(",")
if value.strip()
]
if not any(value.lower() == "authorization" for value in vary_values):
vary_values.append("Authorization")
headers["Vary"] = ", ".join(vary_values)
def _cache_response_headers(
self, request: Request, etag: str, content_type: str | None
) -> dict[str, str]:
cache_control = f"max-age={self.ttl}"
headers = {"ETag": etag, "Cache-Control": cache_control}
if request.headers.get("authorization"):
headers["Cache-Control"] = f"private, {cache_control}"
headers["Vary"] = "Authorization"
if content_type:
headers["Content-Type"] = content_type
return headers
def _is_cacheable_request(self, request: Request) -> bool:
if self._requires_no_store(request):
return False
if request.method == "GET":
return True
if request.method == "POST":
return not request.url.path.startswith(EXCLUDED_POST_PATHS)
return False
async def dispatch(self, request: Request, call_next):
if self._requires_no_store(request):
response = await call_next(request)
self._set_no_store_headers(response)
return response
if not self._is_cacheable_request(request):
return await call_next(request)
async def dispatch(self, request: Request, call_next):
if self._requires_no_store(request):
response = await call_next(request)
self._set_no_store_headers(response)
return response
if not self._is_cacheable_request(request):
return await call_next(request)
body_bytes = b""
if request.method == "POST":
@@ -165,21 +166,21 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
client_etag = request.headers.get("if-none-match")
# Cache hit + not expired
if entry:
if client_etag == entry["etag"]:
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(status_code=304, headers=headers)
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(
if entry:
if client_etag == entry["etag"]:
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(status_code=304, headers=headers)
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(
content=entry["body"],
status_code=entry["status_code"],
headers=headers,
@@ -204,9 +205,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
},
)
headers = self._cache_response_headers(request, etag, content_type)
return Response(
headers = self._cache_response_headers(request, etag, content_type)
return Response(
content=body,
status_code=response.status_code,
headers=headers,
)
)
@@ -71,6 +71,8 @@ model/bundProjectPage.ts
model/careerMetrics.ts
model/careerStage.ts
model/collaborationGraph.ts
model/collaborationGraphStatus.ts
model/collaborationGraphStatusResponse.ts
model/collaborationNetwork.ts
model/collaborationNetworkEdge.ts
model/collaborationNetworkNodeType.ts
@@ -227,6 +229,7 @@ model/rebuildResponse.ts
model/score.ts
model/selectedAuthorsRequest.ts
model/sortDirection.ts
model/startCollaborationGraphResponse.ts
model/subfieldShare.ts
model/timespan.ts
model/tokenType.ts
+68 -9
View File
@@ -19,9 +19,11 @@ import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorPage } from '../model/authorPage';
// @ts-ignore
import { CollaborationGraph } from '../model/collaborationGraph';
import { CollaborationGraphStatusResponse } from '../model/collaborationGraphStatusResponse';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { StartCollaborationGraphResponse } from '../model/startCollaborationGraphResponse';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -157,9 +159,64 @@ export class AuthorsV2Service extends BaseService {
);
}
/**
* Returns the status of a collaboration graph generation task.
* @endpoint get /api/authors/v2/collaboration-graph/{graph_id}/status
* @param graphId The ID of the collaboration graph generation task.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCollaborationGraphStatus(graphId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CollaborationGraphStatusResponse>;
public getCollaborationGraphStatus(graphId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CollaborationGraphStatusResponse>>;
public getCollaborationGraphStatus(graphId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CollaborationGraphStatusResponse>>;
public getCollaborationGraphStatus(graphId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (graphId === null || graphId === undefined) {
throw new Error('Required parameter graphId was null or undefined when calling getCollaborationGraphStatus.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/authors/v2/collaboration-graph/${this.configuration.encodeParam({name: "graphId", value: graphId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/status`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CollaborationGraphStatusResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a collaboration graph for a given author ID.
* @endpoint get /api/authors/v2/collaboration-graph/{raw_oa_author_id}
* @endpoint post /api/authors/v2/collaboration-graph
* @param rawOaAuthorId The raw OpenAlex author ID for which to retrieve the collaboration graph.
* @param yearFrom The starting year to filter the works by (optional).
* @param yearTo The ending year to filter the works by (optional).
@@ -170,15 +227,17 @@ export class AuthorsV2Service extends BaseService {
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CollaborationGraph>;
public getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CollaborationGraph>>;
public getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CollaborationGraph>>;
public getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<StartCollaborationGraphResponse>;
public startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<StartCollaborationGraphResponse>>;
public startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<StartCollaborationGraphResponse>>;
public startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getCollaborationGraph.');
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling startCollaborationGraph.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>rawOaAuthorId, 'raw_oa_author_id');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>yearFrom, 'year_from');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -225,9 +284,9 @@ export class AuthorsV2Service extends BaseService {
}
}
let localVarPath = `/api/authors/v2/collaboration-graph/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
let localVarPath = `/api/authors/v2/collaboration-graph`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CollaborationGraph>('get', `${basePath}${localVarPath}`,
return this.httpClient.request<StartCollaborationGraphResponse>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
@@ -0,0 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const CollaborationGraphStatus = {
Pending: 'pending',
Completed: 'completed',
Failed: 'failed'
} as const;
export type CollaborationGraphStatus = typeof CollaborationGraphStatus[keyof typeof CollaborationGraphStatus];
@@ -0,0 +1,25 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { CollaborationGraph } from './collaborationGraph';
import { CollaborationGraphStatus } from './collaborationGraphStatus';
export interface CollaborationGraphStatusResponse {
/**
* The status of the collaboration graph.
*/
status: CollaborationGraphStatus;
result?: CollaborationGraph | null;
error_message?: string | null;
}
export namespace CollaborationGraphStatusResponse {
}
+3
View File
@@ -37,6 +37,8 @@ export * from './bundProjectPage';
export * from './careerMetrics';
export * from './careerStage';
export * from './collaborationGraph';
export * from './collaborationGraphStatus';
export * from './collaborationGraphStatusResponse';
export * from './collaborationNetwork';
export * from './collaborationNetworkEdge';
export * from './collaborationNetworkNodeType';
@@ -192,6 +194,7 @@ export * from './rebuildResponse';
export * from './score';
export * from './selectedAuthorsRequest';
export * from './sortDirection';
export * from './startCollaborationGraphResponse';
export * from './subfieldShare';
export * from './timespan';
export * from './tokenType';
@@ -0,0 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface StartCollaborationGraphResponse {
/**
* The ID of the collaboration graph.
*/
graph_id: string;
}
+1 -1
View File
@@ -531,7 +531,7 @@ export const routes: Routes = [
(mod) => mod.PersonNetworkComponent,
),
resolve: {
collaborationGraph: collaborationGraphResolver,
startCollaborationGraphResponse: collaborationGraphResolver,
selectedTopics: selectedTopicsResolver,
selectedInstitutions: selectedInstitutionsResolver,
},
@@ -4,87 +4,93 @@
<p>Zusammenarbeit und Verbindungen im wissenschaftlichen Netzwerk.</p>
</div>
<div class="cards">
<mat-card appearance="outlined" style="width: 50%">
<mat-card-content>
<app-collaboration-graph
[collaborationGraph]="collaborationGraph()"
(handleNodeClick)="handleNodeClick($event)" />
</mat-card-content>
</mat-card>
<div class="right-card">
<div class="toggle-group">
<mat-button-toggle-group
class="mat-button-toggle-group"
aria-label="Select view"
(change)="onToggleChange($event)"
[formField]="filterForm2.displayedTable"
style="width: 100%">
<mat-button-toggle value="collaborators">
Kollaborierende
</mat-button-toggle>
<mat-button-toggle value="publications"
>Publikationen</mat-button-toggle
>
<mat-button-toggle value="institutions">
Institutionen
</mat-button-toggle>
</mat-button-toggle-group>
<button
class="filter-button"
mat-stroked-button
type="button"
(click)="openFilterDialog()">
<mat-icon>filter_alt</mat-icon>
Filter
</button>
</div>
<app-query-param-input
style="width: 100%"
queryParamKey="search_term"
[label]="this.searchTermLabel()" />
<app-selected-filters [observers]="observers" [enabledRemoval]="false" />
<mat-card appearance="outlined">
<mat-card-content class="scroll-viewport-container">
@if (this.displayedTable() === 'collaborators') {
<app-data-table
[columns]="collaboratorsColumns"
[data]="collaboratorsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="collaboratorsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'publications') {
<app-data-table
[columns]="publicationsColumns"
[data]="publicationsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="publicationsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'institutions') {
<app-data-table
[columns]="institutionsColumns"
[data]="institutionsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="institutionsDetailRow"
[maxHeight]="'100%'" />
}
@if (!collaborationGraph()) {
<span>Laden...</span>
} @else {
<div class="cards">
<mat-card appearance="outlined" style="width: 50%">
<mat-card-content>
<app-collaboration-graph
[collaborationGraph]="collaborationGraph()!"
(handleNodeClick)="handleNodeClick($event)" />
</mat-card-content>
</mat-card>
</div>
</div>
<div class="summary-container">
@for (summary of this.summaryCards(); track $index) {
<app-info-card
[icon]="summary.icon"
[value]="summary.value.toString()"
[description]="summary.description" />
}
</div>
<div class="right-card">
<div class="toggle-group">
<mat-button-toggle-group
class="mat-button-toggle-group"
aria-label="Select view"
(change)="onToggleChange($event)"
[formField]="filterForm2.displayedTable"
style="width: 100%">
<mat-button-toggle value="collaborators">
Kollaborierende
</mat-button-toggle>
<mat-button-toggle value="publications"
>Publikationen</mat-button-toggle
>
<mat-button-toggle value="institutions">
Institutionen
</mat-button-toggle>
</mat-button-toggle-group>
<button
class="filter-button"
mat-stroked-button
type="button"
(click)="openFilterDialog()">
<mat-icon>filter_alt</mat-icon>
Filter
</button>
</div>
<app-query-param-input
style="width: 100%"
queryParamKey="search_term"
[label]="this.searchTermLabel()" />
<app-selected-filters
[observers]="observers"
[enabledRemoval]="false" />
<mat-card appearance="outlined">
<mat-card-content class="scroll-viewport-container">
@if (this.displayedTable() === 'collaborators') {
<app-data-table
[columns]="collaboratorsColumns"
[data]="collaboratorsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="collaboratorsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'publications') {
<app-data-table
[columns]="publicationsColumns"
[data]="publicationsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="publicationsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'institutions') {
<app-data-table
[columns]="institutionsColumns"
[data]="institutionsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="institutionsDetailRow"
[maxHeight]="'100%'" />
}
</mat-card-content>
</mat-card>
</div>
</div>
<div class="summary-container">
@for (summary of this.summaryCards(); track $index) {
<app-info-card
[icon]="summary.icon"
[value]="summary.value.toString()"
[description]="summary.description" />
}
</div>
}
</div>
<ng-template #collaboratorsActionTmp let-element>
@@ -1,8 +1,13 @@
import { toSignal } from '@angular/core/rxjs-interop';
import {
takeUntilDestroyed,
toObservable,
toSignal,
} from '@angular/core/rxjs-interop';
import {
Component,
computed,
DestroyRef,
effect,
input,
OnInit,
@@ -21,10 +26,13 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import {
AuthorNode,
AuthorsV2Service,
CollaborationGraph,
CollaborationGraphStatus,
Institution,
InstitutionNode,
InstitutionPageV2,
StartCollaborationGraphResponse,
Topic,
TopicPageV2,
WorkNode,
@@ -53,6 +61,7 @@ import {
SelectedFiltersComponent,
} from '../../shared/ui/selected-filters/selected-filters.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
import { from, interval, startWith, switchMap, takeWhile, tap } from 'rxjs';
type DetailedWorkNode = WorkNode & {
authors: AuthorNode[];
@@ -105,7 +114,9 @@ interface FilterData {
providers: [],
})
export class PersonNetworkComponent implements OnInit {
collaborationGraph = input.required<CollaborationGraph>();
startCollaborationGraphResponse =
input.required<StartCollaborationGraphResponse>();
collaborationGraph = signal<CollaborationGraph | undefined>(undefined);
selectedTopics = input.required<TopicPageV2>();
selectedInstitutions = input.required<InstitutionPageV2>();
@@ -188,16 +199,16 @@ export class PersonNetworkComponent implements OnInit {
collaboratorsColumns: GenericColumn<DetailedAuthorNode>[] = [];
collaboratorsData = computed<DetailedAuthorNode[]>(
() =>
this.collaborationGraph().authors?.map((author) => ({
this.collaborationGraph()?.authors?.map((author) => ({
...author,
works: (this.collaborationGraph().works ?? []).filter((work) =>
(this.collaborationGraph().edges ?? []).some(
works: (this.collaborationGraph()?.works ?? []).filter((work) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) => edge.source === author.id && edge.target === work.id,
),
),
institutions: (this.collaborationGraph().institutions ?? []).filter(
institutions: (this.collaborationGraph()?.institutions ?? []).filter(
(institution) =>
(this.collaborationGraph().edges ?? []).some(
(this.collaborationGraph()?.edges ?? []).some(
(edge) =>
edge.source === author.id && edge.target === institution.id,
),
@@ -217,10 +228,10 @@ export class PersonNetworkComponent implements OnInit {
publicationsColumns: GenericColumn<DetailedWorkNode>[] = [];
publicationsData = computed(
() =>
this.collaborationGraph().works?.map((work) => ({
this.collaborationGraph()?.works?.map((work) => ({
...work,
authors: (this.collaborationGraph().authors ?? []).filter((author) =>
(this.collaborationGraph().edges ?? []).some(
authors: (this.collaborationGraph()?.authors ?? []).filter((author) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) => edge.source === author.id && edge.target === work.id,
),
),
@@ -239,10 +250,10 @@ export class PersonNetworkComponent implements OnInit {
institutionsColumns: GenericColumn<DetailedInstitutionNode>[] = [];
institutionsData = computed(
() =>
this.collaborationGraph().institutions?.map((institution) => ({
this.collaborationGraph()?.institutions?.map((institution) => ({
...institution,
authors: (this.collaborationGraph().authors ?? []).filter((author) =>
(this.collaborationGraph().edges ?? []).some(
authors: (this.collaborationGraph()?.authors ?? []).filter((author) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) =>
edge.source === author.id && edge.target === institution.id,
),
@@ -259,12 +270,12 @@ export class PersonNetworkComponent implements OnInit {
'institutionsDetailRow',
);
persons = computed(() => this.collaborationGraph().authors?.length ?? 0);
persons = computed(() => this.collaborationGraph()?.authors?.length ?? 0);
institutions = computed(
() => this.collaborationGraph().institutions?.length ?? 0,
() => this.collaborationGraph()?.institutions?.length ?? 0,
);
publications = computed(() => this.collaborationGraph().works?.length ?? 0);
connections = computed(() => this.collaborationGraph().edges?.length ?? 0);
publications = computed(() => this.collaborationGraph()?.works?.length ?? 0);
connections = computed(() => this.collaborationGraph()?.edges?.length ?? 0);
searchTermLabel = computed(() => {
const displayedTable = this.filterForm2.displayedTable().value();
@@ -350,11 +361,46 @@ export class PersonNetworkComponent implements OnInit {
searchTerm = computed(() => this.queryParamMap().get('search_term') || '');
private readonly POLL_INTERVAL_MS = 3000;
constructor(
private readonly activatedRoute: ActivatedRoute,
private readonly router: Router,
private readonly dialog: MatDialog,
private readonly authorsService: AuthorsV2Service,
private readonly destroyRef: DestroyRef,
) {
toObservable(this.startCollaborationGraphResponse)
.pipe(
switchMap((startResponse) =>
interval(this.POLL_INTERVAL_MS).pipe(
startWith(0),
switchMap(() =>
from(
this.authorsService.getCollaborationGraphStatus(
startResponse.graph_id,
),
),
),
tap((statusResponse) => {
if (
statusResponse.status === CollaborationGraphStatus.Completed &&
statusResponse.result
) {
this.collaborationGraph.set(statusResponse.result);
}
}),
takeWhile((statusResponse) => {
return (
statusResponse.status !== CollaborationGraphStatus.Completed
);
}, true),
),
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe();
effect(() => {
const filters = this.filterModel();
this.router.navigate([], {
@@ -1,5 +1,5 @@
import { ResolveFn } from '@angular/router';
import { AuthorsV2Service, CollaborationGraph } from '../api';
import { AuthorsV2Service, StartCollaborationGraphResponse } from '../api';
import { inject } from '@angular/core';
export const collaborationGraphQueryParamKeys = {
@@ -11,10 +11,9 @@ export const collaborationGraphQueryParamKeys = {
institutionId: 'institutionId',
} as const;
export const collaborationGraphResolver: ResolveFn<CollaborationGraph> = (
route,
state,
) => {
export const collaborationGraphResolver: ResolveFn<
StartCollaborationGraphResponse
> = (route, state) => {
const id = route.parent?.paramMap.get('id');
if (!id) {
throw new Error('No author ID provided in route parameters');
@@ -46,7 +45,7 @@ export const collaborationGraphResolver: ResolveFn<CollaborationGraph> = (
collaborationGraphQueryParamKeys.institutionId,
);
return inject(AuthorsV2Service).getCollaborationGraph(
return inject(AuthorsV2Service).startCollaborationGraph(
id,
yearFrom,
yearTo,