Skip to content

Worker Base

Job(worker: object = None, juuid: str = None, client_address: str = None, timeout: int = None, args: list = None, kwargs: dict = None, task: str = None, client_input_queue: object = None) ¤

Source code in norfab\core\worker.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(
    self,
    worker: object = None,
    juuid: str = None,
    client_address: str = None,
    timeout: int = None,
    args: list = None,
    kwargs: dict = None,
    task: str = None,
    client_input_queue: object = None,
) -> None:
    self.worker = worker
    self.juuid = juuid
    self.client_address = client_address
    self.timeout = timeout
    self.args = args or []
    self.kwargs = kwargs or {}
    self.task = task
    self.client_input_queue = client_input_queue
    self.binary_input_queue = queue.Queue()
    self.start_time = time.time()
    self.pending_input_request = None

fetch_file(url: str, destination: str = None, chunk_size: int = 256000) -> str ¤

Fetch a file when a task needs it, returning a local path.

Parameters:

Name Type Description Default
url str

file://relative or file:///absolute URL on the submitting client, supplied in this job's arguments. nf:// and git:// use the existing FileSharing fetch helper.

required
destination str

Output path for client files; defaults to a unique path under fetchedfiles. FileSharing uses its existing cache.

None
chunk_size int

Bytes per client-file request, from 1 through 1048576.

256000

Returns:

Type Description
str

Local absolute path after size and MD5 verification. Client files

str

are fetched without pre-staging.

Raises:

Type Description
ValueError

Unsupported URL or invalid chunk size.

OSError

File read or write failed; partial files may remain.

TimeoutError

The job deadline expired while fetching.

Source code in norfab\core\worker.py
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
def fetch_file(
    self, url: str, destination: str = None, chunk_size: int = 256000
) -> str:
    """Fetch a file when a task needs it, returning a local path.

    Args:
        url: file://relative or file:///absolute URL on the submitting
            client, supplied in this job's arguments. nf:// and git:// use
            the existing FileSharing fetch helper.
        destination: Output path for client files; defaults to a unique
            path under fetchedfiles. FileSharing uses its existing cache.
        chunk_size: Bytes per client-file request, from 1 through 1048576.

    Returns:
        Local absolute path after size and MD5 verification. Client files
        are fetched without pre-staging.

    Raises:
        ValueError: Unsupported URL or invalid chunk size.
        OSError: File read or write failed; partial files may remain.
        TimeoutError: The job deadline expired while fetching.
    """
    if not url.startswith("file://"):
        return self.worker.fetch_file(url, read=False, raise_on_fail=True)
    self.check_timeout()
    timeout = (
        max(0, self.timeout - (time.time() - self.start_time))
        if self.timeout
        else 600
    )
    destination = destination or os.path.join(
        self.worker.client.base_dir,
        "fetchedfiles",
        uuid4().hex,
        os.path.basename(self.worker.safe_path(url)),
    )

    if not 0 < chunk_size <= 1024 * 1024:
        raise ValueError("chunk_size must be 1..1048576")
    destination = os.path.abspath(destination)
    os.makedirs(os.path.dirname(destination), exist_ok=True)
    deadline = time.monotonic() + timeout
    file_hash = hashlib.md5()
    details = None
    with open(destination, "wb") as target:
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise TimeoutError(f"file transfer timed out: {url}")
            self.worker.send_to_broker(
                NFP.PUT,
                [
                    self.client_address.encode(),
                    b"",
                    self.juuid.encode(),
                    b"200",
                    orjson.dumps(
                        {
                            "file_read": True,
                            "file_details": details is None,
                            "path": url,
                            "worker": self.worker.name,
                            "offset": target.tell(),
                            "size": chunk_size,
                        }
                    ),
                ],
            )
            try:
                status, chunk = self.binary_input_queue.get(timeout=remaining)
            except queue.Empty:
                raise TimeoutError(f"file transfer timed out: {url}") from None
            if status == b"201":
                details = chunk
                continue
            if status != b"200":
                raise OSError(chunk.decode("utf-8", errors="replace"))
            if len(chunk) > chunk_size:
                raise OSError("source returned more bytes than requested")
            if not chunk:
                if (
                    target.tell() != details["size_bytes"]
                    or file_hash.hexdigest() != details["md5hash"]
                ):
                    raise OSError("file transfer failed, size or MD5 hash mismatch")
                break
            target.write(chunk)
            file_hash.update(chunk)
    return destination

is_timed_out() -> bool ¤

Check if the job has exceeded its timeout.

Returns:

Name Type Description
bool bool

True if the job has timed out, False otherwise or if timeout is not set.

Source code in norfab\core\worker.py
191
192
193
194
195
196
197
198
199
def is_timed_out(self) -> bool:
    """Check if the job has exceeded its timeout.

    Returns:
        bool: True if the job has timed out, False otherwise or if timeout is not set.
    """
    if self.timeout is None:
        return False
    return (time.time() - self.start_time) >= self.timeout

check_timeout() -> None ¤

Raise TimeoutError if the job has exceeded its configured timeout.

Jobs without a timeout do not expire. Running operations are not interrupted.

Raises:

Type Description
TimeoutError

The elapsed job runtime has reached its timeout.

Source code in norfab\core\worker.py
201
202
203
204
205
206
207
208
209
210
211
212
213
def check_timeout(self) -> None:
    """Raise TimeoutError if the job has exceeded its configured timeout.

    Jobs without a timeout do not expire. Running operations are not interrupted.

    Raises:
        TimeoutError: The elapsed job runtime has reached its timeout.
    """
    if self.is_timed_out():
        raise TimeoutError(
            f"job '{self.juuid}' task '{self.task}' exceeded its "
            f"{self.timeout}-second timeout"
        )

event(message: str, **kwargs: Any) -> None ¤

Handles an event by forwarding it to the worker.

Parameters:

Name Type Description Default
message str

The message describing the event.

required
**kwargs Any

Additional keyword arguments to include in the event.

{}
Source code in norfab\core\worker.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def event(self, message: str, **kwargs: Any) -> None:
    """
    Handles an event by forwarding it to the worker.

    Args:
        message (str): The message describing the event.
        **kwargs: Additional keyword arguments to include in the event.
    """
    kwargs.setdefault("task", self.task)
    kwargs.setdefault("event_type", "progress")
    if self.juuid and self.worker:
        self.worker.event(
            message=message,
            juuid=self.juuid,
            client_address=self.client_address,
            **kwargs,
        )

stream(data: bytes) -> None ¤

Streams data to the broker.

This method sends a message containing the client address, a unique identifier (UUID), a status code, and the provided data to the broker.

Parameters:

Name Type Description Default
data bytes

The data to be streamed to the broker.

required
Source code in norfab\core\worker.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def stream(self, data: bytes) -> None:
    """
    Streams data to the broker.

    This method sends a message containing the client address, a unique
    identifier (UUID), a status code, and the provided data to the broker.

    Args:
        data (bytes): The data to be streamed to the broker.
    """
    msg = [
        self.client_address.encode("utf-8"),
        b"",
        self.juuid.encode("utf-8"),
        b"200",
        data,
    ]
    self.worker.send_to_broker(NFP.STREAM, msg)

wait_client_input(timeout: int = 10) -> Any ¤

Waits for input from the client within a specified timeout period if no item is available within the specified timeout, it returns None.

Parameters:

Name Type Description Default
timeout int

The maximum time (in seconds) to wait for input

10

Returns:

Name Type Description
Any Any

The item retrieved from the client_input_queue

Source code in norfab\core\worker.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def wait_client_input(self, timeout: int = 10) -> Any:
    """
    Waits for input from the client within a specified timeout period if no item
    is available within the specified timeout, it returns `None`.

    Args:
        timeout (int, optional): The maximum time (in seconds) to wait for input

    Returns:
        Any: The item retrieved from the `client_input_queue`
    """
    try:
        return self.client_input_queue.get(block=True, timeout=timeout)
    except queue.Empty:
        pass

    return None

Task(input: Optional[BaseModel] = None, output: Optional[BaseModel] = None, description: Optional[str] = None, fastapi: Optional[dict] = None, mcp: Optional[dict] = None, agent: Optional[dict] = None) ¤

Validate is a class-based decorator that accept arguments, designed to validate the input arguments of a task function using a specified Pydantic model. It ensures that the arguments passed to the decorated function conform to the schema defined in the model.

Attributes:

Name Type Description
model BaseModel

A Pydantic model used to validate the function arguments.

name str

The name of the task, which is used to register the task for calling, by default set equal to the name of decorated function.

result_model BaseModel

A Pydantic model used to validate the function's return value.

fastapi dict

Dictionary with parameters for FastAPI app.add_api_route method

mcp dict

Dictionary with parameters for MCP mcp.types.Tool class. The optional prompts key is a NorFab extension containing a list of MCP prompt definitions associated with the task. Task validates and normalizes these definitions before registration. FastMCP removes this key before constructing the MCP Tool object. The optional guardrails key is a NorFab extension containing a list of MCP task call guardrails. FastMCP validates these definitions during discovery, removes this key before constructing the MCP Tool object, and evaluates guardrails before dispatching tool calls to NorFab services. The optional result_guardrails key is a NorFab extension containing a list of model-facing task result size and content guardrails. FastMCP validates these definitions during discovery, removes this key before constructing the MCP Tool object, and evaluates them on a copied result after task execution.

Methods:

Name Description
__call__

Callable) -> Callable: Wraps the target function and validates its arguments before execution.

merge_args_to_kwargs

List, kwargs: Dict) -> Dict: Merges positional arguments (args) and keyword arguments (kwargs) into a single dictionary, mapping positional arguments to their corresponding parameter names based on the function's signature.

validate_input

List, kwargs: Dict) -> None: Validates merged arguments against Pydantic model. If validation fails, an exception is raised.

Usage

@Task()(input=YourPydanticModel) def your_function(arg1, arg2, ...): # Function implementation pass

Notes
  • The decorator uses inspect.getfullargspec to analyze the function's signature and properly map arguments for validation.
Source code in norfab\core\worker.py
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
def __init__(
    self,
    input: Optional[BaseModel] = None,
    output: Optional[BaseModel] = None,
    description: Optional[str] = None,
    fastapi: Optional[dict] = None,
    mcp: Optional[dict] = None,
    agent: Optional[dict] = None,
) -> None:
    self.input = input
    self.output = output or Result
    self.description = description
    if fastapi is False:
        self.fastapi = False
    else:
        self.fastapi = fastapi or {}
    if mcp is False:
        self.mcp = False
    else:
        self.mcp = dict(mcp or {})
        if "prompts" in self.mcp:
            validated_prompts = TaskMCPPrompts(prompts=self.mcp["prompts"])
            self.mcp["prompts"] = validated_prompts.model_dump()["prompts"]
    if agent is False:
        self.agent = False
    else:
        self.agent = agent or {}

__call__(function: Callable) -> Callable ¤

Decorator to register a function as a worker task with input/output validation and optional argument filtering.

This method wraps the provided function, validates its input arguments and output, and registers it as a task. It also removes 'job' and 'progress' keyword arguments if the wrapped function does not accept them.

Side Effects:

- Sets self.function, self.description, and self.name based on the provided function.
- Initializes input model if not already set.
- Updates the global NORFAB_WORKER_TASKS with the task schema.
Source code in norfab\core\worker.py
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
def __call__(self, function: Callable) -> Callable:
    """
    Decorator to register a function as a worker task with input/output
    validation and optional argument filtering.

    This method wraps the provided function, validates its input arguments
    and output, and registers it as a task. It also removes 'job' and
    'progress' keyword arguments if the wrapped function does not accept them.

    Side Effects:

        - Sets self.function, self.description, and self.name based on the provided function.
        - Initializes input model if not already set.
        - Updates the global NORFAB_WORKER_TASKS with the task schema.
    """
    self.function = function
    self.description = self.description or function.__doc__
    self.name = function.__name__

    if self.input is None:
        self.make_input_model()

    @functools.wraps(self.function)
    def wrapper(*args: object, **kwargs: object):
        # remove `job` argument if function does not expect it
        if is_need_argument(function, "job") is False:
            _ = kwargs.pop("job", None)

        # remove `progress` argument if function does not expect it
        if is_need_argument(function, "progress") is False:
            _ = kwargs.pop("progress", None)

        # validate input arguments
        self.validate_input(args, kwargs)

        ret = self.function(*args, **kwargs)

        # validate result
        self.validate_output(ret)

        return ret

    NORFAB_WORKER_TASKS.update(self.make_task_schema(wrapper))

    log.debug(
        f"{function.__module__} PID {os.getpid()} registered task '{function.__name__}'"
    )

    return wrapper

make_input_model() -> None ¤

Dynamically creates a Pydantic input model for the worker's function by inspecting its signature.

This method uses inspect.getfullargspec to extract the function's argument names, default values, keyword-only arguments, and type annotations. It then constructs a dictionary of field specifications, giving preference to type annotations where available, and excluding special parameters such as 'self', 'return', 'job', and any *args or **kwargs. The resulting specification is used to create a Pydantic model, which is assigned to self.input.

The generated model used for input validation.

Source code in norfab\core\worker.py
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
def make_input_model(self) -> None:
    """
    Dynamically creates a Pydantic input model for the worker's function by inspecting its signature.

    This method uses `inspect.getfullargspec` to extract the function's argument names, default values,
    keyword-only arguments, and type annotations. It then constructs a dictionary of field specifications,
    giving preference to type annotations where available, and excluding special parameters such as 'self',
    'return', 'job', and any *args or **kwargs. The resulting specification is used to create a Pydantic
    model, which is assigned to `self.input`.

    The generated model used for input validation.
    """
    (
        fun_args,  # list of the positional parameter names
        fun_varargs,  # name of the * parameter or None
        fun_varkw,  # name of the ** parameter or None
        fun_defaults,  # tuple of default argument values of the last n positional parameters
        fun_kwonlyargs,  # list of keyword-only parameter names
        fun_kwonlydefaults,  # dictionary mapping kwonlyargs parameter names to default values
        fun_annotations,  # dictionary mapping parameter names to annotations
    ) = inspect.getfullargspec(self.function)

    # form a dictionary keyed by args with their default values
    args_with_defaults = dict(
        zip(reversed(fun_args or []), reversed(fun_defaults or []))
    )

    # form a dictionary keyed by args that has no defaults with values set to
    # (Any, None) tuple if make_optional is True else set to (Any, ...)
    args_no_defaults = {
        k: (Any, ...) for k in fun_args if k not in args_with_defaults
    }

    # form dictionary keyed by args with annotations and tuple values
    args_with_hints = {
        k: (v, args_with_defaults.get(k, ...)) for k, v in fun_annotations.items()
    }

    # form merged kwargs giving preference to type hint annotations
    merged_kwargs = {**args_no_defaults, **args_with_defaults, **args_with_hints}

    # form final dictionary of fields
    fields_spec = {
        k: v
        for k, v in merged_kwargs.items()
        if k not in ["self", "return", "job", fun_varargs, fun_varkw]
    }

    log.debug(
        f"NorFab worker {self.name} task creating Pydantic input "
        f"model using fields spec: {fields_spec}"
    )

    # create Pydantic model
    self.input = create_model(self.name, **fields_spec)

make_task_schema(wrapper) -> dict ¤

Generates a task schema dictionary for the current worker.

Parameters:

Name Type Description Default
wrapper Callable

The function wrapper to be associated with the task.

required

Returns:

Name Type Description
dict dict

A dictionary containing the task's metadata, including: - function: The provided wrapper function. - module: The module name where the original function is defined. - schema: A dictionary with the following keys: - name (str): The name of the task. - description (str): The description of the task. - inputSchema (dict): The JSON schema for the input model. - outputSchema (dict): The JSON schema for the output model. - fastapi: FastAPI-specific metadata. - mcp: Model Context protocol metadata

Source code in norfab\core\worker.py
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
def make_task_schema(self, wrapper) -> dict:
    """
    Generates a task schema dictionary for the current worker.

    Args:
        wrapper (Callable): The function wrapper to be associated with the task.

    Returns:
        dict: A dictionary containing the task's metadata, including:
            - function: The provided wrapper function.
            - module: The module name where the original function is defined.
            - schema: A dictionary with the following keys:
                - name (str): The name of the task.
                - description (str): The description of the task.
                - inputSchema (dict): The JSON schema for the input model.
                - outputSchema (dict): The JSON schema for the output model.
                - fastapi: FastAPI-specific metadata.
                - mcp: Model Context protocol metadata
    """
    input_json_schema = self.input.model_json_schema(by_alias=False)
    _ = input_json_schema.pop("title")
    output_json_schema = self.output.model_json_schema(by_alias=False)

    return {
        self.name: {
            "function": wrapper,
            "module": self.function.__module__,
            "schema": {
                "name": str(self.name),
                "description": self.description,
                "inputSchema": input_json_schema,
                "outputSchema": output_json_schema,
                "fastapi": self.fastapi,
                "mcp": self.mcp,
                "agent": self.agent,
            },
        }
    }

merge_args_to_kwargs(args: List, kwargs: Dict) -> Dict ¤

Merges positional arguments (args) and keyword arguments (kwargs) into a single dictionary.

This function uses the argument specification of the decorated function to ensure that all arguments are properly combined into a dictionary. This is particularly useful for scenarios where **kwargs need to be passed to another function or model (e.g., for validation purposes).

Parameters:

Name Type Description Default
args list

A list of positional arguments passed to the decorated function.

required
kwargs dict

A dictionary of keyword arguments passed to the decorated function.

required
Return

dict: A dictionary containing the merged arguments, where positional arguments are mapped to their corresponding parameter names.

Source code in norfab\core\worker.py
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
def merge_args_to_kwargs(self, args: List, kwargs: Dict) -> Dict:
    """
    Merges positional arguments (`args`) and keyword arguments (`kwargs`)
    into a single dictionary.

    This function uses the argument specification of the decorated function
    to ensure that all arguments are properly combined into a dictionary.
    This is particularly useful for scenarios where **kwargs need to be passed
    to another function or model (e.g., for validation purposes).

    Arguments:
        args (list): A list of positional arguments passed to the decorated function.
        kwargs (dict): A dictionary of keyword arguments passed to the decorated function.

    Return:
        dict: A dictionary containing the merged arguments, where positional arguments
              are mapped to their corresponding parameter names.
    """
    merged_kwargs = {}

    (
        fun_args,  # list of the positional parameter names
        fun_varargs,  # name of the * parameter or None
        *_,  # ignore the rest
    ) = inspect.getfullargspec(self.function)

    # "def foo(a, b):" - combine "foo(1, 2)" args with "a, b" fun_args
    args_to_kwargs = dict(zip(fun_args, args))

    # "def foo(a, *b):" - combine "foo(1, 2, 3)" 2|3 args with "*b" fun_varargs
    if fun_varargs:
        args_to_kwargs[fun_varargs] = args[len(fun_args) :]

    merged_kwargs = {**kwargs, **args_to_kwargs}

    # remove reference to self if decorating class method
    _ = merged_kwargs.pop("self", None)

    return merged_kwargs

validate_input(args: List, kwargs: Dict) -> None ¤

Function to validate provided arguments against model

Source code in norfab\core\worker.py
719
720
721
722
723
724
725
726
727
def validate_input(self, args: List, kwargs: Dict) -> None:
    """Function to validate provided arguments against model"""
    merged_kwargs = self.merge_args_to_kwargs(args, kwargs)
    log.debug(f"{self.name} validating input arguments: {merged_kwargs}")
    # if below step succeeds, kwargs passed model validation
    _ = self.input(**merged_kwargs)
    log.debug(
        f"Validated input kwargs: {merged_kwargs} for function {self.function} using model {self.input}"
    )

JobDatabase(db_path: str, jobs_compress: bool = True) ¤

Thread-safe SQLite database manager for worker jobs.

Handles all job persistence operations with proper thread safety through connection-level locking and WAL mode for concurrent reads.

Attributes:

Name Type Description
db_path str

Path to the SQLite database file.

_local local

Thread-local storage for database connections.

_lock Lock

Lock for write operations to ensure thread safety.

Initialize the job database.

Parameters:

Name Type Description Default
db_path str

Path to the SQLite database file.

required
jobs_compress bool

If True, compress args, kwargs, and result_data fields. Defaults to True.

True
Source code in norfab\core\worker.py
753
754
755
756
757
758
759
760
761
762
763
764
765
def __init__(self, db_path: str, jobs_compress: bool = True) -> None:
    """
    Initialize the job database.

    Args:
        db_path (str): Path to the SQLite database file.
        jobs_compress (bool): If True, compress args, kwargs, and result_data fields. Defaults to True.
    """
    self.db_path = db_path
    self.jobs_compress = jobs_compress
    self._local = threading.local()
    self._lock = threading.Lock()
    self._initialize_database()

add_job(uuid: str, client_address: str, task: str, args: list, kwargs: dict, timeout: int, timestamp: str) -> None ¤

Add a new job to the database.

Parameters:

Name Type Description Default
uuid str

Job UUID.

required
client_address str

Client address.

required
task str

Task name.

required
args list

Task arguments.

required
kwargs dict

Task keyword arguments.

required
timeout int

Job timeout.

required
timestamp str

Received timestamp.

required
Source code in norfab\core\worker.py
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
def add_job(
    self,
    uuid: str,
    client_address: str,
    task: str,
    args: list,
    kwargs: dict,
    timeout: int,
    timestamp: str,
) -> None:
    """
    Add a new job to the database.

    Args:
        uuid (str): Job UUID.
        client_address (str): Client address.
        task (str): Task name.
        args (list): Task arguments.
        kwargs (dict): Task keyword arguments.
        timeout (int): Job timeout.
        timestamp (str): Received timestamp.
    """
    now = time.strftime("%Y-%m-%d %H:%M:%S")
    with self._transaction(write=True) as conn:
        # Serialize args and kwargs to BLOB
        compressed_args = self._compress_data({"args": args})
        compressed_kwargs = self._compress_data({"kwargs": kwargs})

        conn.execute(
            """
            INSERT INTO jobs (uuid, client_address, task, args, kwargs, timeout,
                             status, received_timestamp, created_at)
            VALUES (?, ?, ?, ?, ?, ?, 'PENDING', ?, ?)
        """,
            (
                uuid,
                client_address,
                task,
                compressed_args,
                compressed_kwargs,
                timeout,
                timestamp,
                now,
            ),
        )

get_next_pending_job() -> tuple ¤

Get the next pending job and mark it as STARTED.

Returns:

Name Type Description
tuple tuple

(uuid, received_timestamp) or None if no pending jobs.

Source code in norfab\core\worker.py
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
def get_next_pending_job(self) -> tuple:
    """
    Get the next pending job and mark it as STARTED.

    Returns:
        tuple: (uuid, received_timestamp) or None if no pending jobs.
    """
    with self._transaction(write=True) as conn:
        # order jobs by their creation timestamp in ascending order - oldest first
        cursor = conn.execute("""
            SELECT uuid, received_timestamp FROM jobs
            WHERE status = 'PENDING'
            ORDER BY created_at ASC
            LIMIT 1
        """)
        row = cursor.fetchone()
        if row:
            uuid = row["uuid"]
            conn.execute(
                """
                UPDATE jobs SET status = 'STARTED', started_timestamp = ?
                WHERE uuid = ?
            """,
                (time.ctime(), uuid),
            )
            return uuid, row["received_timestamp"]
        return None

complete_job(uuid: str, result_data: dict) -> None ¤

Mark a job as completed and store its result.

Parameters:

Name Type Description Default
uuid str

Job UUID.

required
result_data dict

Result data as dictionary.

required
Source code in norfab\core\worker.py
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
def complete_job(self, uuid: str, result_data: dict) -> None:
    """
    Mark a job as completed and store its result.

    Args:
        uuid (str): Job UUID.
        result_data (dict): Result data as dictionary.
    """
    try:
        compressed_result_data = self._compress_data(result_data)
    except Exception as e:
        for wname, wres in result_data["result"].items():
            wres["errors"] = [
                f"Worker experienced error while compressing job results data: '{e}'"
            ]
            wres["failed"] = True
            wres["result"] = {}
        self.fail_job(uuid, result_data)
    else:
        with self._transaction(write=True) as conn:
            conn.execute(
                """
                UPDATE jobs
                SET status = 'COMPLETED', completed_timestamp = ?, result_data = ?
                WHERE uuid = ?
            """,
                (time.ctime(), compressed_result_data, uuid),
            )

fail_job(uuid: str, result_data: dict) -> None ¤

Mark a job as failed and store its result.

Parameters:

Name Type Description Default
uuid str

Job UUID.

required
result_data dict

Result data as dictionary.

required
Source code in norfab\core\worker.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
def fail_job(self, uuid: str, result_data: dict) -> None:
    """
    Mark a job as failed and store its result.

    Args:
        uuid (str): Job UUID.
        result_data (dict): Result data as dictionary.
    """
    with self._transaction(write=True) as conn:
        conn.execute(
            """
            UPDATE jobs
            SET status = 'FAILED', completed_timestamp = ?, result_data = ?
            WHERE uuid = ?
            """,
            (time.ctime(), self._compress_data(result_data), uuid),
        )

get_job_info(uuid: str, include_result: bool = False, include_events: bool = False) -> dict ¤

Get comprehensive job information including status, execution data, and optionally result data and events.

Parameters:

Name Type Description Default
uuid str

Job UUID.

required
include_result bool

If True, include result_data in the response. Defaults to False.

False
include_events bool

If True, include job events. Defaults to False.

False

Returns:

Name Type Description
dict dict

Job information with the following fields: - uuid: Job UUID - status: Job status (PENDING, STARTED, COMPLETED, FAILED, WAITING_CLIENT_INPUT) - received_timestamp: When job was received - started_timestamp: When job started execution - completed_timestamp: When job completed - client_address: Client address - task: Task name - args: Parsed task arguments list - kwargs: Parsed task keyword arguments dict - timeout: Job timeout

dict

If include_result=True, also includes: - result_data: Result data dictionary (if available)

dict

If include_events=True, also includes: - job_events: List of event dictionaries

dict

Returns None if job not found.

Source code in norfab\core\worker.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def get_job_info(
    self,
    uuid: str,
    include_result: bool = False,
    include_events: bool = False,
) -> dict:
    """
    Get comprehensive job information including status, execution data, and optionally result data and events.

    Args:
        uuid (str): Job UUID.
        include_result (bool): If True, include result_data in the response. Defaults to False.
        include_events (bool): If True, include job events. Defaults to False.

    Returns:
        dict: Job information with the following fields:
            - uuid: Job UUID
            - status: Job status (PENDING, STARTED, COMPLETED, FAILED, WAITING_CLIENT_INPUT)
            - received_timestamp: When job was received
            - started_timestamp: When job started execution
            - completed_timestamp: When job completed
            - client_address: Client address
            - task: Task name
            - args: Parsed task arguments list
            - kwargs: Parsed task keyword arguments dict
            - timeout: Job timeout

        If include_result=True, also includes:
            - result_data: Result data dictionary (if available)

        If include_events=True, also includes:
            - job_events: List of event dictionaries

        Returns None if job not found.
    """
    with self._transaction(write=False) as conn:
        # Build SELECT clause based on requested fields
        select_fields = [
            "uuid",
            "status",
            "received_timestamp",
            "started_timestamp",
            "completed_timestamp",
            "client_address",
            "task",
            "args",
            "kwargs",
            "timeout",
        ]

        if include_result:
            select_fields.append("result_data")

        query = f"""
            SELECT {', '.join(select_fields)}
            FROM jobs WHERE uuid = ?
        """

        cursor = conn.execute(query, (uuid,))
        row = cursor.fetchone()

        if not row:
            return None

        result = dict(row)
        result.setdefault("result_data", None)
        result.setdefault("job_events", [])

        # Deserialize args and kwargs from BLOB
        result["args"] = self._decompress_data(row["args"]).get("args", [])
        result["kwargs"] = self._decompress_data(row["kwargs"]).get("kwargs", {})

        # Include result data if requested
        if include_result and row["result_data"]:
            result["result_data"] = self._decompress_data(row["result_data"])

        # Include events if requested
        if include_events:
            result["job_events"] = self.get_job_events(uuid)

        return result

add_event(job_uuid: str, message: str, severity: str, task: str, event_data: dict) -> None ¤

Add an event for a job.

Parameters:

Name Type Description Default
job_uuid str

Job UUID.

required
message str

Event message.

required
severity str

Event severity.

required
task str

Task name.

required
event_data dict

Event data dictionary.

required
Source code in norfab\core\worker.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
def add_event(
    self, job_uuid: str, message: str, severity: str, task: str, event_data: dict
) -> None:
    """
    Add an event for a job.

    Args:
        job_uuid (str): Job UUID.
        message (str): Event message.
        severity (str): Event severity.
        task (str): Task name.
        event_data (dict): Event data dictionary.
    """
    with self._transaction(write=True) as conn:
        conn.execute(
            """
            INSERT INTO events (job_uuid, message, severity, task, event_data)
            VALUES (?, ?, ?, ?, ?)
        """,
            (
                job_uuid,
                message,
                severity,
                task,
                orjson.dumps(event_data).decode("utf-8"),
            ),
        )

get_job_events(uuid: str) -> list ¤

Get all events for a job.

Parameters:

Name Type Description Default
uuid str

Job UUID.

required

Returns:

Name Type Description
list list

List of event dictionaries.

Source code in norfab\core\worker.py
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
def get_job_events(self, uuid: str) -> list:
    """
    Get all events for a job.

    Args:
        uuid (str): Job UUID.

    Returns:
        list: List of event dictionaries.
    """
    with self._transaction(write=False) as conn:
        cursor = conn.execute(
            """
            SELECT message, severity, task, event_data, created_at
            FROM events WHERE job_uuid = ?
            ORDER BY created_at ASC
        """,
            (uuid,),
        )
        return [
            {
                "message": row["message"],
                "severity": row["severity"],
                "task": row["task"],
                **orjson.loads(row["event_data"]),
                "created_at": row["created_at"],
            }
            for row in cursor.fetchall()
        ]

list_jobs(pending: bool = True, completed: bool = True, task: str = None, last: int = None, client: str = None, uuid: str = None) -> list ¤

List jobs based on filters.

Parameters:

Name Type Description Default
pending bool

Include pending jobs.

True
completed bool

Include completed jobs.

True
task str

Filter by task name.

None
last int

Return only last N jobs.

None
client str

Filter by client address.

None
uuid str

Filter by specific UUID.

None

Returns:

Name Type Description
list list

List of job dictionaries.

Source code in norfab\core\worker.py
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
def list_jobs(
    self,
    pending: bool = True,
    completed: bool = True,
    task: str = None,
    last: int = None,
    client: str = None,
    uuid: str = None,
) -> list:
    """
    List jobs based on filters.

    Args:
        pending (bool): Include pending jobs.
        completed (bool): Include completed jobs.
        task (str): Filter by task name.
        last (int): Return only last N jobs.
        client (str): Filter by client address.
        uuid (str): Filter by specific UUID.

    Returns:
        list: List of job dictionaries.
    """
    with self._transaction(write=False) as conn:
        # Build query
        conditions = []
        params = []

        if uuid:
            conditions.append("uuid = ?")
            params.append(uuid)
        else:
            status_conditions = []
            if pending:
                status_conditions.append(
                    "status IN ('PENDING', 'STARTED', 'WAITING_CLIENT_INPUT')"
                )
            if completed:
                status_conditions.append("status IN ('COMPLETED', 'FAILED')")
            if status_conditions:
                conditions.append(f"({' OR '.join(status_conditions)})")

            if task:
                conditions.append("task = ?")
                params.append(task)
            if client:
                conditions.append("client_address = ?")
                params.append(client)

        where_clause = f"WHERE {' AND '.join(conditions)}" if conditions else ""
        query = f"""
            SELECT uuid, client_address, task, status,
                   received_timestamp, started_timestamp, completed_timestamp
            FROM jobs {where_clause}
            ORDER BY created_at DESC
        """

        if last:
            query += f" LIMIT {last}"

        cursor = conn.execute(query, params)
        return [dict(row) for row in cursor.fetchall()]

jobs_stats() -> dict ¤

Return counts of all retained jobs, grouped by status.

Counts persist across restarts and decrease when job history is removed. Failed jobs are counted separately from completed jobs.

Returns:

Name Type Description
dict dict

Total job count and a mapping of statuses to job counts.

Source code in norfab\core\worker.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
def jobs_stats(self) -> dict:
    """Return counts of all retained jobs, grouped by status.

    Counts persist across restarts and decrease when job history is removed.
    Failed jobs are counted separately from completed jobs.

    Returns:
        dict: Total job count and a mapping of statuses to job counts.
    """
    with self._transaction(write=False) as conn:
        rows = conn.execute("SELECT status, COUNT(*) FROM jobs GROUP BY status")
        jobs_by_status = {row[0]: row[1] for row in rows.fetchall()}
    return {
        "total_jobs": sum(jobs_by_status.values()),
        "jobs_by_status": jobs_by_status,
    }

close() -> None ¤

Close all database connections.

Source code in norfab\core\worker.py
1266
1267
1268
1269
1270
def close(self) -> None:
    """Close all database connections."""
    if hasattr(self._local, "conn"):
        self._local.conn.close()
        delattr(self._local, "conn")

NFPWorker(inventory: NorFabInventory, broker: str, service: str, name: str, exit_event: object, log_level: str = None, multiplier: int = 6, keepalive: int = 2500) ¤

NFPWorker class is responsible for managing worker operations, including connecting to a broker, handling jobs, and maintaining keepalive connections. It interacts with the broker using ZeroMQ and manages job queues and events.

Parameters:

Name Type Description Default
inventory NorFabInventory

The inventory object containing base directory information.

required
broker str

The broker address.

required
service str

The service name.

required
name str

The name of the worker.

required
exit_event object

The event used to signal the worker to exit.

required
log_level str

Logging level configured from worker inventory.

None
multiplier int

The multiplier value. Defaults to 6.

6
keepalive int

The keepalive interval in milliseconds. Defaults to 2500.

2500
Source code in norfab\core\worker.py
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
def __init__(
    self,
    inventory: NorFabInventory,
    broker: str,
    service: str,
    name: str,
    exit_event: object,
    log_level: str = None,
    multiplier: int = 6,
    keepalive: int = 2500,
) -> None:
    self.inventory = inventory
    self.name = name
    self.setup_logging(log_level)
    self.max_concurrent_jobs = max(1, inventory.get("max_concurrent_jobs", 5))
    self.jobs_compress = inventory.get("jobs_compress", True)
    self.autostart_watchdog = inventory.get("autostart_watchdog", True)
    self.broker = broker
    self.service = service.encode("utf-8") if isinstance(service, str) else service
    self.exit_event = exit_event
    self.broker_socket = None
    self.multiplier = multiplier
    self.keepalive = keepalive
    self.zmq_auth = self.inventory.broker.get("zmq_auth", True)
    self.build_message = NFP.MessageBuilder()
    self.monitoring = ProcessMonitor()
    self.public_keys_dir = None
    self.secret_keys_dir = None
    self.worker_private_key_file = None
    self.broker_public_key_file = None

    # create base directories
    self.base_dir = os.path.join(
        self.inventory.base_dir, "__norfab__", "files", "worker", self.name
    )
    os.makedirs(self.base_dir, exist_ok=True)

    # Initialize SQLite database for job management
    db_path = os.path.join(self.base_dir, f"{self.name}.db")
    self.db = JobDatabase(db_path, jobs_compress=self.jobs_compress)

    # dictionary to store currently running jobs
    self.running_jobs = {}
    self.status = {
        "sid_inventory_status": None,
    }

    # create events and queues
    self.destroy_event = threading.Event()
    self.pending_job_event = threading.Event()
    self.request_thread = None
    self.reply_thread = None
    self.recv_thread = None
    self.event_thread = None
    self.put_thread = None

    self.post_queue = queue.Queue(maxsize=0)
    self.get_queue = queue.Queue(maxsize=0)
    self.delete_queue = queue.Queue(maxsize=0)
    self.event_queue = queue.Queue(maxsize=0)
    self.put_queue = queue.Queue(maxsize=0)
    self.outbound_queue = queue.Queue(maxsize=NFP.OUTBOUND_QUEUE_SIZE)

    # generate certificates and create directories
    if self.zmq_auth is not False:
        generate_certificates(
            self.base_dir,
            cert_name=self.name,
            broker_keys_dir=os.path.join(
                self.inventory.base_dir,
                "__norfab__",
                "files",
                "broker",
                "public_keys",
            ),
            inventory=self.inventory,
        )
        self.public_keys_dir = os.path.join(self.base_dir, "public_keys")
        self.secret_keys_dir = os.path.join(self.base_dir, "private_keys")

    self.ctx = zmq.Context()
    self.poller = zmq.Poller()
    self.wakeup_reader, self.wakeup_writer = socket.socketpair()
    self.wakeup_reader.setblocking(False)
    self.wakeup_writer.setblocking(False)
    self.poller.register(self.wakeup_reader, zmq.POLLIN)
    self.reconnect_to_broker()

    self.client = NFPClient(
        self.inventory,
        self.broker,
        name=f"{self.name}-NFPClient",
        exit_event=self.exit_event,
    )

    self.tasks = NORFAB_WORKER_TASKS

    # initiate watchdog
    if self.autostart_watchdog and self.autostart_base_watchdog:
        self.watchdog = WorkerWatchDog(self)
        self.watchdog.start()

setup_logging(log_level: str = None) -> dict ¤

Configure logging for this worker process.

The worker uses the logging inventory it received during construction as a per-process template and writes its default NorFab file sink to __norfab__/logs/worker-<worker-name>.jsonl.

Parameters:

Name Type Description Default
log_level str

Optional logging level override.

None

Returns:

Name Type Description
dict dict

Logging configuration applied to this process.

Source code in norfab\core\worker.py
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
def setup_logging(self, log_level: str = None) -> dict:
    """
    Configure logging for this worker process.

    The worker uses the logging inventory it received during construction
    as a per-process template and writes its default NorFab file sink to
    ``__norfab__/logs/worker-<worker-name>.jsonl``.

    Args:
        log_level: Optional logging level override.

    Returns:
        dict: Logging configuration applied to this process.
    """
    return setup_process_logging(
        base_dir=self.inventory.base_dir,
        role="worker",
        name=self.name,
        log_level=log_level,
        inventory_logging=self.inventory.logging,
    )

reconnect_to_broker(queue_ready: bool = True) -> list | None ¤

Connect or reconnect to the broker.

This method handles the connection or reconnection process to the broker. It performs the following steps:

  1. If there is an existing broker socket, unregisters it from the poller and closes it.
  2. Creates a new DEALER socket and sets its identity.
  3. Loads the client's secret and public keys for CURVE authentication.
  4. Loads the server's public key for CURVE authentication.
  5. Connects the socket to the broker.
  6. Registers the socket with the poller for incoming messages.
  7. Builds a READY message to register the service.
  8. Starts or restarts the keepalive mechanism to maintain the connection.
  9. Increments the reconnect statistics counter.
  10. Logs the successful registration to the broker.

Parameters:

Name Type Description Default
queue_ready bool

If True, queue the READY frame. If False, return the READY frame so the socket owner can send it immediately before any queued worker messages.

True
Source code in norfab\core\worker.py
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
def reconnect_to_broker(self, queue_ready: bool = True) -> list | None:
    """
    Connect or reconnect to the broker.

    This method handles the connection or reconnection process to the broker.
    It performs the following steps:

    1. If there is an existing broker socket, unregisters it from the poller
       and closes it.
    2. Creates a new DEALER socket and sets its identity.
    3. Loads the client's secret and public keys for CURVE authentication.
    4. Loads the server's public key for CURVE authentication.
    5. Connects the socket to the broker.
    6. Registers the socket with the poller for incoming messages.
    7. Builds a READY message to register the service.
    8. Starts or restarts the keepalive mechanism to maintain the connection.
    9. Increments the reconnect statistics counter.
    10. Logs the successful registration to the broker.

    Args:
        queue_ready: If True, queue the READY frame. If False, return the
            READY frame so the socket owner can send it immediately before
            any queued worker messages.
    """
    if self.broker_socket:
        self.poller.unregister(self.broker_socket)
        self.broker_socket.close()

    self.broker_socket = self.ctx.socket(zmq.DEALER)
    self.broker_socket.setsockopt_unicode(zmq.IDENTITY, self.name, "utf8")
    self.broker_socket.linger = 0

    if self.zmq_auth is not False:
        # We need two certificates, one for the client and one for
        # the server. The client must know the server's public key
        # to make a CURVE connection.
        self.worker_private_key_file = os.path.join(
            self.secret_keys_dir, f"{self.name}.key_secret"
        )
        client_public, client_secret = zmq.auth.load_certificate(
            self.worker_private_key_file
        )
        self.broker_socket.curve_secretkey = client_secret
        self.broker_socket.curve_publickey = client_public

        # The client must know the server's public key to make a CURVE connection.
        self.broker_public_key_file = os.path.join(
            self.public_keys_dir, "broker.key"
        )
        server_public, _ = zmq.auth.load_certificate(self.broker_public_key_file)
        self.broker_socket.curve_serverkey = server_public

    self.broker_socket.connect(self.broker)
    self.poller.register(self.broker_socket, zmq.POLLIN)

    # Register service with broker
    ready_msg = self.build_message.worker_to_broker_ready(service=self.service)
    if queue_ready:
        self.outbound_queue.put(
            ready_msg, block=True, timeout=NFP.OUTBOUND_QUEUE_TIMEOUT
        )
        try:
            self.wakeup_writer.send(b"\x00")
        except BlockingIOError:
            pass  # A pending notification already guarantees a wake-up.
    log.debug(f"{self.name} - NFP.READY prepared for broker '{self.broker}'")

    if self.keepaliver is not None:
        self.keepaliver.restart()
    else:
        self.keepaliver = KeepAliver(
            address=None,
            multiplier=self.multiplier,
            keepalive=self.keepalive,
            exit_event=self.destroy_event,
            service=self.service,
            whoami=NFP.WORKER,
            name=self.name,
        )
        self.keepaliver.start()

    self.monitoring.record_reconnect()
    log.info(
        f"{self.name} - registered to broker at '{self.broker}', "
        f"service '{self.service.decode('utf-8')}'"
    )
    return None if queue_ready else ready_msg

send_to_broker(command: str, msg: list = None) -> None ¤

Send a message to the broker.

Parameters:

Name Type Description Default
command str

The command to send to the broker. Must be one of NFP.READY, NFP.DISCONNECT, NFP.RESPONSE, or NFP.EVENT.

required
msg list

The message to send. If not provided, a default message will be created based on the command.

None
Logs

Logs an error if the command is unsupported. Logs a debug message with the message being sent.

Thread Safety

This method is thread-safe because non-owner threads only submit prepared messages to the outbound queue. The zmq_send_recv thread owns the ZeroMQ socket.

Source code in norfab\core\worker.py
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
def send_to_broker(self, command: str, msg: list = None) -> None:
    """
    Send a message to the broker.

    Parameters:
        command (str): The command to send to the broker. Must be one of NFP.READY, NFP.DISCONNECT, NFP.RESPONSE, or NFP.EVENT.
        msg (list, optional): The message to send. If not provided, a default message will be created based on the command.

    Logs:
        Logs an error if the command is unsupported.
        Logs a debug message with the message being sent.

    Thread Safety:
        This method is thread-safe because non-owner threads only submit
        prepared messages to the outbound queue. The zmq_send_recv thread
        owns the ZeroMQ socket.
    """
    if command == NFP.READY:
        msg = self.build_message.worker_to_broker_ready(service=self.service)
    elif command == NFP.DISCONNECT:
        msg = self.build_message.worker_to_broker_disconnect(service=self.service)
    elif command == NFP.RESPONSE:
        msg = self.build_message.worker_to_broker_response(response_data=msg)
    elif command == NFP.EVENT:
        msg = self.build_message.worker_to_broker_event(event_data=msg)
    elif command == NFP.STREAM:
        msg = self.build_message.worker_to_broker_stream(data=msg)
    elif command == NFP.PUT:
        msg = [b"", NFP.WORKER, command] + msg
    else:
        log.error(
            f"{self.name} - cannot send '{command}' to broker, command unsupported"
        )
        return

    log.debug(f"{self.name} - queueing '{msg}'")

    if self.destroy_event.is_set():
        return

    try:
        self.outbound_queue.put_nowait(msg)
    except queue.Full:
        log.warning(
            f"{self.name} - outbound queue is full, dropping '{command}' "
            f"message to broker"
        )
        return

    try:
        self.wakeup_writer.send(b"\x00")
    except BlockingIOError:
        pass  # A pending notification already guarantees a wake-up.
    except OSError:
        if not self.destroy_event.is_set():
            raise

load_inventory() -> dict ¤

Load inventory data from the broker for this worker.

This function retrieves inventory data from the broker service using the worker's name. It logs the received inventory data and returns the results if available.

Returns:

Name Type Description
dict dict

The inventory data results if available, otherwise an empty dictionary.

Source code in norfab\core\worker.py
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
def load_inventory(self) -> dict:
    """
    Load inventory data from the broker for this worker.

    This function retrieves inventory data from the broker service using the worker's name.
    It logs the received inventory data and returns the results if available.

    Returns:
        dict: The inventory data results if available, otherwise an empty dictionary.
    """
    self.status["sid_inventory_status"] = "initialising"
    try:
        inventory_data = self.client.mmi(
            "sid.service.broker", "get_inventory", kwargs={"name": self.name}
        )
    except Exception:
        self.status["sid_inventory_status"] = "failed"
        raise

    log.debug(f"{self.name} - worker received inventory data {inventory_data}")

    self.status["sid_inventory_status"] = (
        "failed" if inventory_data.get("errors") else "completed"
    )

    if inventory_data["results"]:
        return inventory_data["results"]
    else:
        return {}

worker_exit() -> None ¤

Method to override in child classes with a set of actions to perform on exit call.

This method should be implemented by subclasses to define any cleanup or finalization tasks that need to be performed when the worker is exiting.

Source code in norfab\core\worker.py
1965
1966
1967
1968
1969
1970
1971
1972
def worker_exit(self) -> None:
    """
    Method to override in child classes with a set of actions to perform on exit call.

    This method should be implemented by subclasses to define any cleanup or finalization
    tasks that need to be performed when the worker is exiting.
    """
    return None

get_inventory(job: Job) -> Result ¤

Retrieve the worker's inventory.

This method should be overridden in child classes to provide the specific implementation for retrieving the inventory of a worker.

Returns:

Name Type Description
Dict Result

A dictionary representing the worker's inventory.

Raises:

Type Description
NotImplementedError

If the method is not overridden in a child class.

Source code in norfab\core\worker.py
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
@Task(fastapi={"methods": ["GET"]})
def get_inventory(self, job: Job) -> Result:
    """
    Retrieve the worker's inventory.

    This method should be overridden in child classes to provide the specific
    implementation for retrieving the inventory of a worker.

    Returns:
        Dict: A dictionary representing the worker's inventory.

    Raises:
        NotImplementedError: If the method is not overridden in a child class.
    """
    raise NotImplementedError

get_version() -> Result ¤

Retrieve the version report of the worker.

This method should be overridden in child classes to provide the specific version report of the worker.

Returns:

Name Type Description
Dict Result

A dictionary containing the version information of the worker.

Raises:

Type Description
NotImplementedError

If the method is not overridden in a child class.

Source code in norfab\core\worker.py
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
@Task(fastapi={"methods": ["GET"]})
def get_version(self) -> Result:
    """
    Retrieve the version report of the worker.

    This method should be overridden in child classes to provide the specific
    version report of the worker.

    Returns:
        Dict: A dictionary containing the version information of the worker.

    Raises:
        NotImplementedError: If the method is not overridden in a child class.
    """
    raise NotImplementedError

destroy(message: str = None) -> None ¤

Cleanly shuts down the worker by performing the following steps:

  1. Calls the worker_exit method to handle any worker-specific exit procedures.
  2. Sets the destroy_event to signal that the worker is being destroyed.
  3. Calls the destroy method on the client to clean up client resources.
  4. Joins all the threads (request_thread, reply_thread, event_thread, recv_thread) if they are not None, ensuring they have finished execution.
  5. Closes the database connections.
  6. Destroys the context with a linger period of 0 to immediately close all sockets.
  7. Stops the keepaliver to cease any keepalive signals.
  8. Logs an informational message indicating that the worker has been destroyed, including an optional message.

Parameters:

Name Type Description Default
message str

An optional message to include in the log when the worker is destroyed.

None
Source code in norfab\core\worker.py
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
def destroy(self, message: str = None) -> None:
    """
    Cleanly shuts down the worker by performing the following steps:

    1. Calls the worker_exit method to handle any worker-specific exit procedures.
    2. Sets the destroy_event to signal that the worker is being destroyed.
    3. Calls the destroy method on the client to clean up client resources.
    4. Joins all the threads (request_thread, reply_thread, event_thread, recv_thread) if they are not None, ensuring they have finished execution.
    5. Closes the database connections.
    6. Destroys the context with a linger period of 0 to immediately close all sockets.
    7. Stops the keepaliver to cease any keepalive signals.
    8. Logs an informational message indicating that the worker has been destroyed, including an optional message.

    Args:
        message (str, optional): An optional message to include in the log when the worker is destroyed.
    """
    self.worker_exit()
    self.destroy_event.set()
    try:
        self.wakeup_writer.send(b"\x00")
    except BlockingIOError:
        pass  # A pending notification will wake the socket thread.
    self.client.destroy()

    # join all the threads
    if self.request_thread is not None:
        self.request_thread.join()
    if self.reply_thread is not None:
        self.reply_thread.join()
    if self.event_thread is not None:
        self.event_thread.join()
    if self.put_thread is not None:
        self.put_thread.join()
    if self.recv_thread:
        self.recv_thread.join()

    # close database
    self.db.close()

    self.poller.unregister(self.wakeup_reader)
    self.wakeup_reader.close()
    self.wakeup_writer.close()
    self.ctx.destroy(0)

    # stop keepalives
    self.keepaliver.stop()

    log.info(f"{self.name} - worker destroyed, message: '{message}'")

safe_path(url: str) -> str ¤

Resolve native paths or a confined FileSharing publication URL.

Parameters:

Name Type Description Default
url str

Plain path, file:// URL, or FileSharing-only nf:// URL.

required

Returns:

Type Description
str

Absolute native path. Only nf:// paths are confined to base_dir;

str

native paths require trusted filesystem access.

Raises:

Type Description
ValueError

Unsupported scheme, non-FileSharing nf:// request, or a published path outside the publication root.

Source code in norfab\core\worker.py
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
def safe_path(self, url: str) -> str:
    """Resolve native paths or a confined FileSharing publication URL.

    Args:
        url: Plain path, file:// URL, or FileSharing-only nf:// URL.

    Returns:
        Absolute native path. Only nf:// paths are confined to base_dir;
        native paths require trusted filesystem access.

    Raises:
        ValueError: Unsupported scheme, non-FileSharing nf:// request, or
            a published path outside the publication root.
    """
    if url.startswith("nf://"):
        if self.service != b"filesharing":
            raise ValueError("nf:// paths require a FileSharing worker")
        relative = url.removeprefix("nf://").replace("\\", "/").lstrip("/\\")
        base = os.path.realpath(self.base_dir)
        path = os.path.realpath(os.path.join(base, *relative.split("/")))
        if os.path.commonpath([base, path]) != base:
            raise ValueError(f"'{url}' - invalid URL path")
        return path
    if "://" in url and not url.startswith("file://"):
        raise ValueError("invalid URL format")
    path = unquote(url[7:]) if url.startswith("file://") else url
    if os.name == "nt" and len(path) > 2 and path[0] == "/" and path[2] == ":":
        path = path[1:]
    return os.path.abspath(path)

list_files(url: str) -> Result ¤

List immediate directory entries on this worker.

Parameters:

Name Type Description Default
url str

Native directory path, file:// URL, or published nf:// directory on a FileSharing worker.

required

Returns:

Type Description
Result

Entry names, including hidden entries, without recursion. Invalid,

Result

missing, or unreadable directories produce a failed result.

Source code in norfab\core\worker.py
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
@Task(
    input=models.ListFilesInput,
    output=models.ListFilesResult,
    fastapi=False,
    mcp=False,
    agent={"enabled": False},
)
def list_files(self, url: str) -> Result:
    """List immediate directory entries on this worker.

    Args:
        url: Native directory path, file:// URL, or published nf:// directory
            on a FileSharing worker.

    Returns:
        Entry names, including hidden entries, without recursion. Invalid,
        missing, or unreadable directories produce a failed result.
    """
    try:
        path = self.safe_path(url)
        if not os.path.isdir(path):
            return Result(result=None, failed=True, errors=["Directory Not Found"])
        return Result(result=os.listdir(path))
    except (OSError, ValueError) as exc:
        return Result(result=None, failed=True, errors=[str(exc)])

walk(url: str) -> Result ¤

Recursively list files on this worker.

Parameters:

Name Type Description Default
url str

Native directory path, file:// URL, or published nf:// directory on a FileSharing worker.

required

Returns:

Type Description
Result

Absolute native paths, or nf:// URLs for published input. Filenames

Result

starting with a dot and roots containing two or more double-underscore

Result

markers are omitted. Directory symlinks are not followed. Invalid or

Result

missing roots produce failed results; os.walk skips inaccessible children.

Source code in norfab\core\worker.py
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
@Task(
    input=models.WalkInput,
    output=models.WalkResult,
    fastapi=False,
    mcp=False,
    agent={"enabled": False},
)
def walk(self, url: str) -> Result:
    """Recursively list files on this worker.

    Args:
        url: Native directory path, file:// URL, or published nf:// directory
            on a FileSharing worker.

    Returns:
        Absolute native paths, or nf:// URLs for published input. Filenames
        starting with a dot and roots containing two or more double-underscore
        markers are omitted. Directory symlinks are not followed. Invalid or
        missing roots produce failed results; os.walk skips inaccessible children.
    """
    try:
        path = self.safe_path(url)
        if not os.path.isdir(path):
            return Result(result=None, failed=True, errors=["Directory Not Found"])
        files_list = []
        for root, _directories, files in os.walk(path):
            if root.count("__") >= 2:
                continue
            for filename in files:
                if filename.startswith("."):
                    continue
                file_path = os.path.join(root, filename)
                if url.startswith("nf://"):
                    relative = os.path.relpath(
                        file_path, os.path.realpath(self.base_dir)
                    )
                    files_list.append("nf://" + relative.replace(os.sep, "/"))
                else:
                    files_list.append(file_path)
        return Result(result=files_list)
    except (OSError, ValueError) as exc:
        return Result(result=None, failed=True, errors=[str(exc)])

file_stat(url: str | list[str]) -> Result ¤

Return size and MD5 for local or published files.

Parameters:

Name Type Description Default
url str | list[str]

A path, file URL, or list of paths/URLs. FileSharing workers also accept nf:// paths within their publication directory.

required

Returns:

Type Description
Result

For a string, metadata containing md5hash, size_bytes, and exists.

Result

For a list, per-URL results with independent failures and collected

Result

errors. Missing, unreadable, or unsafe files produce failed entries;

Result

an empty list returns no entries. MD5 detects corruption, not authenticity.

Source code in norfab\core\worker.py
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
@Task(
    input=models.FileStatInput,
    output=models.FileStatResult,
    fastapi=False,
    mcp=False,
    agent={"enabled": False},
)
def file_stat(self, url: str | list[str]) -> Result:
    """Return size and MD5 for local or published files.

    Args:
        url: A path, file URL, or list of paths/URLs. FileSharing workers
            also accept nf:// paths within their publication directory.

    Returns:
        For a string, metadata containing md5hash, size_bytes, and exists.
        For a list, per-URL results with independent failures and collected
        errors. Missing, unreadable, or unsafe files produce failed entries;
        an empty list returns no entries. MD5 detects corruption, not authenticity.
    """
    urls = [url] if isinstance(url, str) else url
    ret = Result(result={})
    for item in urls:
        entry = Result(
            result={"md5hash": None, "size_bytes": None, "exists": False}
        )
        try:
            full_path = self.safe_path(item)
            if not os.path.isfile(full_path):
                entry.failed = True
                entry.errors = [f"'{item}' file not found"]
            else:
                file_hash = hashlib.md5()
                size = 0
                with open(full_path, "rb") as file_obj:
                    chunk = file_obj.read(8192)
                    while chunk:
                        file_hash.update(chunk)
                        size += len(chunk)
                        chunk = file_obj.read(8192)
                entry.result = {
                    "md5hash": file_hash.hexdigest(),
                    "size_bytes": size,
                    "exists": True,
                }
        except (OSError, ValueError) as exc:
            entry.failed = True
            entry.errors = [str(exc)]
        ret.errors.extend(entry.errors)
        ret.result[item] = entry.model_dump()
    if isinstance(url, str):
        return entry
    return ret

serve_file(job: Job, path: str, chunk_size: int = 256000) -> Result ¤

Serve requested ranges within one ordinary job.

Parameters:

Name Type Description Default
job Job

Running job whose PUT inputs request chunks and whose STREAM messages carry bytes. The existing job timeout bounds the transfer.

required
path str

Local path or file URL on this worker, read afresh per chunk. FileSharing workers also accept nf:// within their publication root.

required
chunk_size int

Bytes per requested chunk, from 1 through 1048576.

256000

Returns:

Type Description
Result

True after the final chunk (empty for an empty file). Bytes are not persisted

Result

as job results. Serving occupies a job slot until completion.

Raises:

Type Description
ValueError

An nf:// URL is unsafe or used on a non-FileSharing worker.

OSError

Source read or receiving client write failed.

TimeoutError

No range request arrived before the job deadline.

Source code in norfab\core\worker.py
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
@Task(
    input=models.ServeFileInput,
    output=models.ServeFileResult,
    fastapi=False,
    mcp=False,
    agent={"enabled": False},
)
def serve_file(self, job: Job, path: str, chunk_size: int = 256000) -> Result:
    """Serve requested ranges within one ordinary job.

    Args:
        job: Running job whose PUT inputs request chunks and whose STREAM
            messages carry bytes. The existing job timeout bounds the transfer.
        path: Local path or file URL on this worker, read afresh per chunk.
            FileSharing workers also accept nf:// within their publication root.
        chunk_size: Bytes per requested chunk, from 1 through 1048576.

    Returns:
        True after the final chunk (empty for an empty file). Bytes are not persisted
        as job results. Serving occupies a job slot until completion.

    Raises:
        ValueError: An nf:// URL is unsafe or used on a non-FileSharing worker.
        OSError: Source read or receiving client write failed.
        TimeoutError: No range request arrived before the job deadline.
    """
    path = self.safe_path(path)
    size = os.path.getsize(path)
    while True:
        job.check_timeout()
        remaining = (
            job.timeout - (time.time() - job.start_time) if job.timeout else 600
        )
        request = job.wait_client_input(timeout=max(0, remaining))
        if request is None:
            raise TimeoutError(f"file transfer timed out: {path}")
        if request.get("error"):
            raise OSError(request["error"])
        offset = request["offset"]
        if type(offset) is not int or offset < 0:
            raise ValueError("offset must be a nonnegative integer")
        with open(path, "rb") as source:
            source.seek(offset)
            chunk = source.read(chunk_size)
        if len(chunk) < min(chunk_size, size - request["offset"]):
            raise OSError("source file changed during transfer")
        job.stream(chunk)
        if not chunk or request["offset"] + len(chunk) >= size:
            return Result(result=True)

receive_file(job: Job, url: str, destination: str = None, source_worker: str = None, chunk_size: int = 256000) -> Result ¤

Pull a file from the submitting client or an explicitly named worker.

Parameters:

Name Type Description Default
job Job

Running job providing client routing and its deadline.

required
url str

Client file URL, source worker path, or existing nf:// or git:// URL.

required
destination str

Local output path, overwritten if present. Defaults to a unique fetchedfiles path for generic transfers. FileSharing URLs retain their existing cache location.

None
source_worker str

Exact source worker name. When omitted, file:// URLs refer to the submitting client.

None
chunk_size int

Bytes per generic chunk, from 1 through 1048576.

256000

Returns:

Type Description
Result

Result containing the absolute local path after transfer completes.

Raises:

Type Description
OSError

Source read or destination write failed; partial files remain.

TimeoutError

Transfer deadline expired.

ValueError

Unsupported URL or invalid chunk size.

Source code in norfab\core\worker.py
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
@Task(
    input=models.ReceiveFileInput,
    output=models.ReceiveFileResult,
    fastapi=False,
    mcp=False,
    agent={"enabled": False},
)
def receive_file(
    self,
    job: Job,
    url: str,
    destination: str = None,
    source_worker: str = None,
    chunk_size: int = 256000,
) -> Result:
    """Pull a file from the submitting client or an explicitly named worker.

    Args:
        job: Running job providing client routing and its deadline.
        url: Client file URL, source worker path, or existing nf:// or git:// URL.
        destination: Local output path, overwritten if present. Defaults to
            a unique fetchedfiles path for generic transfers. FileSharing
            URLs retain their existing cache location.
        source_worker: Exact source worker name. When omitted, file:// URLs
            refer to the submitting client.
        chunk_size: Bytes per generic chunk, from 1 through 1048576.

    Returns:
        Result containing the absolute local path after transfer completes.

    Raises:
        OSError: Source read or destination write failed; partial files remain.
        TimeoutError: Transfer deadline expired.
        ValueError: Unsupported URL or invalid chunk size.
    """
    if source_worker:
        result = self.client.fetch_file(
            url,
            worker=source_worker,
            destination=destination,
            timeout=job.timeout or 600,
            chunk_size=chunk_size,
        )
        if result["status"] != "200":
            raise OSError(result["error"])
        path = result["content"]
    else:
        path = job.fetch_file(url, destination, chunk_size)
    return Result(result=path)

is_url(url: str) -> bool ¤

Check if the given string is a URL supported by NorFab File Service.

Parameters:

Name Type Description Default
url str

The URL to check.

required

Returns:

Name Type Description
bool bool

True if the URL supported by NorFab File Service, False otherwise.

Source code in norfab\core\worker.py
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
def is_url(self, url: str) -> bool:
    """
    Check if the given string is a URL supported by NorFab File Service.

    Args:
        url (str): The URL to check.

    Returns:
        bool: True if the URL supported by NorFab File Service, False otherwise.
    """
    return any(str(url).startswith(k) for k in ["nf://", "git://"])

fetch_file(url: str | list[str], raise_on_fail: bool = False, read: bool = True) -> str | None | list[str | None] ¤

Fetch one or more published files through the worker's client.

Parameters:

Name Type Description Default
url str | list[str]

An nf:// or git:// URL, or a list of URLs.

required
raise_on_fail bool

Raise after fetching if any URL failed. Defaults to False.

False
read bool

Return text content when True (default), otherwise local paths.

True

Returns:

Type Description
str | None | list[str | None]

File content or path for a string URL, or a list in input order for

str | None | list[str | None]

a URL list, preserving duplicate positions. Failed entries are None.

str | None | list[str | None]

An empty list returns an empty list without submitting jobs.

Raises:

Type Description
TypeError

If url is neither a string nor a list of strings.

ValueError

If a single URL has an unsupported scheme.

FileNotFoundError

If raise_on_fail is True and any file failed.

Source code in norfab\core\worker.py
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
def fetch_file(
    self, url: str | list[str], raise_on_fail: bool = False, read: bool = True
) -> str | None | list[str | None]:
    """Fetch one or more published files through the worker's client.

    Args:
        url: An nf:// or git:// URL, or a list of URLs.
        raise_on_fail: Raise after fetching if any URL failed. Defaults to False.
        read: Return text content when True (default), otherwise local paths.

    Returns:
        File content or path for a string URL, or a list in input order for
        a URL list, preserving duplicate positions. Failed entries are None.
        An empty list returns an empty list without submitting jobs.

    Raises:
        TypeError: If url is neither a string nor a list of strings.
        ValueError: If a single URL has an unsupported scheme.
        FileNotFoundError: If raise_on_fail is True and any file failed.
    """
    single = isinstance(url, str)
    if single and not self.is_url(url):
        raise ValueError(f"Invalid URL format: {url}")
    results = self.client.fetch_file(url=url, read=read)
    urls = [url] if single else url
    results = [results] if single else results
    failed = []
    content = []
    for item, result in zip(urls, results):
        content.append(result["content"] if result["status"] == "200" else None)
        if result["status"] != "200":
            message = f"{self.name} - fetching '{item}' failed: {result['error']}"
            log.error(message)
            failed.append(item)
    if failed and raise_on_fail:
        raise FileNotFoundError(f"failed to fetch files: {', '.join(failed)}")
    return content[0] if single else content

jinja2_render_templates(templates: list[str], context: dict = None, filters: dict = None, template_cache: dict = None) -> str ¤

Download (if needed) and render a list of Jinja2 templates with the given context and optional filters.

Parameters:

Name Type Description Default
templates list[str]

A list of Jinja2 template strings or NorFab file paths.

required
context dict

A dictionary containing the context variables for rendering the templates.

None
filters dict

A dictionary of custom Jinja2 filters to be used during rendering.

None
template_cache dict

Cache of compiled Jinja2 file templates keyed by resolved NorFab file URL.

None

Returns:

Name Type Description
str str

The rendered templates concatenated into a single string.

Source code in norfab\core\worker.py
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
def jinja2_render_templates(
    self,
    templates: list[str],
    context: dict = None,
    filters: dict = None,
    template_cache: dict = None,
) -> str:
    """
    Download (if needed) and render a list of Jinja2 templates with the given context and optional filters.

    Args:
        templates (list[str]): A list of Jinja2 template strings or NorFab file paths.
        context (dict): A dictionary containing the context variables for rendering the templates.
        filters (dict, optional): A dictionary of custom Jinja2 filters to be used during rendering.
        template_cache (dict, optional): Cache of compiled Jinja2 file templates
            keyed by resolved NorFab file URL.

    Returns:
        str: The rendered templates concatenated into a single string.
    """
    rendered = []
    filters = filters or {}
    context = context or {}
    template_cache = template_cache if template_cache is not None else {}
    for template in templates:
        if any(marker in template for marker in ("{{", "{%", "{#")):
            j2env = Environment(loader="BaseLoader")
            j2env.filters.update(filters)  # add custom filters
            renderer = j2env.from_string(template)
            template = renderer.render(**context)
        # download template file and render it again
        if self.is_url(template):
            renderer = template_cache.get(template)
            if renderer is None:
                filepath = self.jinja2_fetch_template(template)
                searchpath, filename = os.path.split(filepath)
                j2env = Environment(loader=FileSystemLoader(searchpath))
                j2env.filters.update(filters)  # add custom filters
                renderer = j2env.get_template(filename)
                template_cache[template] = renderer
            rendered.append(renderer.render(**context))
        # template content is fully rendered
        else:
            rendered.append(template)

    return "\n".join(rendered)

jinja2_fetch_template(url: str) -> str ¤

Helper function to recursively download a Jinja2 template along with other templates referenced using "include" statements.

Parameters:

Name Type Description Default
url str

An nf:// or git:// URL to download.

required

Returns:

Name Type Description
str str

The file path of the downloaded Jinja2 template.

Raises:

Type Description
FileNotFoundError

If the file download fails.

Exception

If Jinja2 template parsing fails.

Source code in norfab\core\worker.py
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
def jinja2_fetch_template(self, url: str) -> str:
    """
    Helper function to recursively download a Jinja2 template along with
    other templates referenced using "include" statements.

    Args:
        url (str): An ``nf://`` or ``git://`` URL to download.

    Returns:
        str: The file path of the downloaded Jinja2 template.

    Raises:
        FileNotFoundError: If the file download fails.
        Exception: If Jinja2 template parsing fails.
    """
    filepath = self.fetch_file(url, read=False)
    if filepath is None:
        msg = f"{self.name} - file download failed '{url}'"
        raise FileNotFoundError(msg)

    # load Jinja2 template content to parse "include"-ed files
    with open(filepath, "r", encoding="utf-8") as f:
        content = f.read()
    j2env = Environment(loader="BaseLoader")
    try:
        parsed_content = j2env.parse(content)
    except Exception as e:
        msg = f"{self.name} - Jinja2 template parsing failed '{url}', error: '{e}'"
        raise Exception(msg)

    # run recursion on include statements
    for node in parsed_content.find_all(Include):
        include_file = node.template.value
        base_url = url.rsplit("/", 1)[0]
        self.jinja2_fetch_template(f"{base_url}/{include_file}")

    return filepath

event(message: str, juuid: str, task: str, client_address: str, **kwargs: Any) -> None ¤

Handles the creation and emission of an event.

This method takes event data, processes it, and sends it to the event queue. It also saves the event data to the database for future reference.

Parameters:

Name Type Description Default
message str

The event message

required
juuid str

Job ID for which this event is generated

required
task str

Task name

required
client_address str

Client address

required
**kwargs Any

Additional keyword arguments to be passed when creating a NorFabEvent instance

{}
Logs

Error: Logs an error message if the event data cannot be formed.

Source code in norfab\core\worker.py
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
def event(
    self,
    message: str,
    juuid: str,
    task: str,
    client_address: str,
    **kwargs: Any,
) -> None:
    """
    Handles the creation and emission of an event.

    This method takes event data, processes it, and sends it to the event queue.
    It also saves the event data to the database for future reference.

    Args:
        message: The event message
        juuid: Job ID for which this event is generated
        task: Task name
        client_address: Client address
        **kwargs: Additional keyword arguments to be passed when creating a NorFabEvent instance

    Logs:
        Error: Logs an error message if the event data cannot be formed.
    """
    kwargs.setdefault("event_type", "progress")
    # construct NorFabEvent
    try:
        event_data = NorFabEvent(
            message=message,
            juuid=juuid,
            client_address=client_address,
            task=task,
            **kwargs,
        )
    except Exception as e:
        log.error(f"Failed to form event data, error {e}")
        return
    event_dict = event_data.model_dump(exclude_none=True)

    # emit event to the broker
    self.event_queue.put(copy.deepcopy(event_dict))

    # check if need to emit log for this event
    if self.inventory["logging"].get("log_events", False):
        event_log = f"EVENT {self.name}:{task} - {message}"
        severity = event_dict.get("severity", "INFO")
        if severity == "INFO":
            log.info(event_log)
        elif severity == "DEBUG":
            log.debug(event_log)
        elif severity == "WARNING":
            log.warning(event_log)
        elif severity == "CRITICAL":
            log.critical(event_log)
        elif severity == "ERROR":
            log.error(event_log)

    # save event to database
    try:
        self.db.add_event(
            job_uuid=juuid,
            message=message,
            severity=event_dict.get("severity", "INFO"),
            task=task,
            event_data=event_dict,
        )
    except Exception as e:
        log.error(f"Failed to save event to database: {e}")

job_details(uuid: str = None, result: bool = True, events: bool = True) -> Result ¤

Method to get job details by UUID for completed jobs.

Parameters:

Name Type Description Default
uuid str

The job UUID to return details for.

None
result bool

If True, return job result.

True
events bool

If True, return job events.

True

Returns:

Name Type Description
Result Result

A Result object with the job details.

Source code in norfab\core\worker.py
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
@Task(fastapi={"methods": ["GET"]}, agent={"enabled": False})
def job_details(
    self,
    uuid: str = None,
    result: bool = True,
    events: bool = True,
) -> Result:
    """
    Method to get job details by UUID for completed jobs.

    Args:
        uuid (str): The job UUID to return details for.
        result (bool): If True, return job result.
        events (bool): If True, return job events.

    Returns:
        Result: A Result object with the job details.
    """
    job = self.db.get_job_info(
        uuid=uuid, include_result=result, include_events=events
    )

    if job:
        return Result(
            task=f"{self.name}:job_details",
            result=job,
        )
    else:
        raise RuntimeError(f"{self.name} - job with UUID '{uuid}' not found")

job_list(pending: bool = True, completed: bool = True, task: str = None, last: int = None, client: str = None, uuid: str = None) -> Result ¤

Method to list worker jobs completed and pending.

Parameters:

Name Type Description Default
pending bool

If True or None, return pending jobs. If False, skip pending jobs.

True
completed bool

If True or None, return completed jobs. If False, skip completed jobs.

True
task str

If provided, return only jobs with this task name.

None
last int

If provided, return only the last N completed and last N pending jobs.

None
client str

If provided, return only jobs submitted by this client.

None
uuid str

If provided, return only the job with this UUID.

None

Returns:

Name Type Description
Result Result

Result object with a list of jobs.

Source code in norfab\core\worker.py
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
@Task(fastapi={"methods": ["GET"]}, agent={"enabled": False})
def job_list(
    self,
    pending: bool = True,
    completed: bool = True,
    task: str = None,
    last: int = None,
    client: str = None,
    uuid: str = None,
) -> Result:
    """
    Method to list worker jobs completed and pending.

    Args:
        pending (bool): If True or None, return pending jobs. If False, skip pending jobs.
        completed (bool): If True or None, return completed jobs. If False, skip completed jobs.
        task (str, optional): If provided, return only jobs with this task name.
        last (int, optional): If provided, return only the last N completed and last N pending jobs.
        client (str, optional): If provided, return only jobs submitted by this client.
        uuid (str, optional): If provided, return only the job with this UUID.

    Returns:
        Result: Result object with a list of jobs.
    """
    jobs = self.db.list_jobs(
        pending=pending,
        completed=completed,
        task=task,
        last=last,
        client=client,
        uuid=uuid,
    )

    # Add worker and service information to each job
    for job in jobs:
        job["worker"] = self.name
        job["service"] = self.service.decode("utf-8")
        # Map database status to expected status names
        if job["status"] in ("PENDING", "STARTED"):
            job["status"] = "PENDING"
            job["completed_timestamp"] = None
        elif job["status"] in ("COMPLETED", "FAILED"):
            job["status"] = "COMPLETED"

    return Result(
        task=f"{self.name}:job_list",
        result=jobs,
    )

get_logs(last: int = 100, level: str = None, logger: str = None, since: str = None, until: str = None) -> Result ¤

Return this worker process JSONL log records.

Parameters:

Name Type Description Default
last int

Return the last N records after filtering.

100
level str

Filter by log severity.

None
logger str

Filter by logger name.

None
since str

Return records at or after this timestamp.

None
until str

Return records at or before this timestamp.

None

Returns:

Name Type Description
Result Result

Log records from this worker's process log file.

Source code in norfab\core\worker.py
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
@Task(fastapi={"methods": ["GET"]}, agent={"enabled": False})
def get_logs(
    self,
    last: int = 100,
    level: str = None,
    logger: str = None,
    since: str = None,
    until: str = None,
) -> Result:
    """
    Return this worker process JSONL log records.

    Args:
        last: Return the last N records after filtering.
        level: Filter by log severity.
        logger: Filter by logger name.
        since: Return records at or after this timestamp.
        until: Return records at or before this timestamp.

    Returns:
        Result: Log records from this worker's process log file.
    """
    records = read_jsonl_logs(
        logs_dir=os.path.join(self.inventory.base_dir, "__norfab__", "logs"),
        log_files=[f"worker-{self.name}.jsonl"],
        last=last,
        level=level,
        logger=logger,
        since=since,
        until=until,
    )
    for record in records:
        record.setdefault("role", "worker")
        record.setdefault("name", self.name)

    return Result(
        task=f"{self.name}:get_logs",
        result=records,
    )

echo(job: Job, raise_error: Union[bool, int, str] = None, sleep: int = None, *args: Any, **kwargs: Any) -> Result ¤

Echoes the job information and optional arguments, optionally sleeping or raising an error.

Parameters:

Name Type Description Default
job Job

The job instance containing job details.

required
raise_error str

If provided, raises a RuntimeError with this message.

None
sleep int

If provided, sleeps for the specified number of seconds.

None
*args Any

Additional positional arguments to include in the result.

()
**kwargs Any

Additional keyword arguments to include in the result.

{}

Returns:

Name Type Description
Result Result

An object containing job details and any provided arguments.

Raises:

Type Description
RuntimeError

If raise_error is provided.

Source code in norfab\core\worker.py
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
@Task(
    fastapi={"methods": ["POST"]},
    input=models.WorkerEchoIn,
    output=models.WorkerEchoOut,
)
def echo(
    self,
    job: Job,
    raise_error: Union[bool, int, str] = None,
    sleep: int = None,
    *args: Any,
    **kwargs: Any,
) -> Result:
    """
    Echoes the job information and optional arguments, optionally sleeping or raising an error.

    Args:
        job (Job): The job instance containing job details.
        raise_error (str, optional): If provided, raises a RuntimeError with this message.
        sleep (int, optional): If provided, sleeps for the specified number of seconds.
        *args: Additional positional arguments to include in the result.
        **kwargs: Additional keyword arguments to include in the result.

    Returns:
        Result: An object containing job details and any provided arguments.

    Raises:
        RuntimeError: If `raise_error` is provided.
    """
    if sleep:
        time.sleep(sleep)
    if raise_error:
        raise RuntimeError(raise_error)
    return Result(
        result={
            "juuid": job.juuid,
            "client_address": job.client_address,
            "timeout": job.timeout,
            "task": job.task,
            "args": args,
            "kwargs": kwargs,
        }
    )

run_shell_cmd(job: Job, command: str, timeout: int = None) -> Result ¤

Runs a shell command on the worker host.

Parameters:

Name Type Description Default
command str

Shell command to execute.

required
timeout int

Maximum command runtime in seconds.

None

Returns:

Name Type Description
Result Result

Command execution details including stdout, stderr, and return code.

Source code in norfab\core\worker.py
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
@Task(
    fastapi={"methods": ["POST"]},
    mcp=False,
    agent={"enabled": False},
)
def run_shell_cmd(self, job: Job, command: str, timeout: int = None) -> Result:
    """
    Runs a shell command on the worker host.

    Args:
        command (str): Shell command to execute.
        timeout (int, optional): Maximum command runtime in seconds.

    Returns:
        Result: Command execution details including stdout, stderr, and return code.
    """
    try:
        proc = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=timeout,
        )
    except subprocess.TimeoutExpired as exc:
        return Result(
            failed=True,
            status="failed",
            errors=[f"Command timed out after {timeout} seconds"],
            result={
                "command": command,
                "stdout": exc.stdout or "",
                "stderr": exc.stderr or "",
                "returncode": None,
                "timeout": timeout,
                "timed_out": True,
            },
        )

    failed = proc.returncode != 0
    return Result(
        failed=failed,
        errors=[proc.stderr] if failed and proc.stderr else [],
        result={
            "command": command,
            "stdout": proc.stdout,
            "stderr": proc.stderr,
            "returncode": proc.returncode,
            "timeout": timeout,
            "timed_out": False,
        },
    )

list_tasks(name: Union[None, str] = None, brief: bool = False) -> Result ¤

Lists tasks supported by worker.

Parameters:

Name Type Description Default
name str

The name of a specific task to retrieve

None
brief bool

If True, returns only the list of task names

False

Returns:

Type Description
Result

Results returned controlled by this logic:

  • If brief is True returns a list of task names
  • If name is provided returns list with single item - OpenAPI schema of the specified task
  • Otherwise returns a list of schemas for all tasks

Raises:

Type Description
KeyError

If a specific task name is provided but not registered in NORFAB_WORKER_TASKS.

Source code in norfab\core\worker.py
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
@Task(fastapi={"methods": ["GET"]}, agent={"enabled": False})
def list_tasks(self, name: Union[None, str] = None, brief: bool = False) -> Result:
    """
    Lists tasks supported by worker.

    Args:
        name (str, optional): The name of a specific task to retrieve
        brief (bool, optional): If True, returns only the list of task names

    Returns:
        Results returned controlled by this logic:

            - If brief is True returns a list of task names
            - If name is provided returns list with single item - OpenAPI schema of the specified task
            - Otherwise returns a list of schemas for all tasks

    Raises:
        KeyError: If a specific task name is provided but not registered in NORFAB_WORKER_TASKS.
    """
    ret = Result()
    if brief:
        ret.result = list(sorted(NORFAB_WORKER_TASKS.keys()))
    elif name:
        if name not in NORFAB_WORKER_TASKS:
            raise KeyError(f"{name} - task not registered")
        ret.result = [NORFAB_WORKER_TASKS[name]["schema"]]
    else:
        ret.result = [t["schema"] for t in NORFAB_WORKER_TASKS.values()]
    return ret

get_worker_status() -> Result ¤

Return worker identity, runtime paths, and security configuration.

Source code in norfab\core\worker.py
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
@Task(fastapi={"methods": ["GET"]}, agent={"enabled": False})
def get_worker_status(self) -> Result:
    """Return worker identity, runtime paths, and security configuration."""
    return Result(
        result={
            "name": self.name,
            "role": "worker",
            "service": self.service.decode("utf-8"),
            "status": ("active" if not self.exit_event.is_set() else "stopping"),
            "broker": self.broker,
            "directories": {
                "base_dir": self.base_dir,
                "public_keys_dir": self.public_keys_dir,
                "private_keys_dir": self.secret_keys_dir,
            },
            "security": {
                "worker_private_key_file": self.worker_private_key_file,
                "broker_public_key_file": self.broker_public_key_file,
                "zmq_auth": self.zmq_auth,
            },
        }
    )

get_stats() -> Result ¤

Return process monitoring and retained job counts.

Job counts cover the worker's SQLite history across restarts, with no time window or record limit. Removing history reduces these counts.

Returns:

Name Type Description
Result Result

Validated monitoring snapshot, including total jobs and counts by status under jobs. Failed jobs are counted separately from completed jobs.

Source code in norfab\core\worker.py
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
@Task(fastapi={"methods": ["GET"]}, agent={"enabled": False})
def get_stats(self) -> Result:
    """Return process monitoring and retained job counts.

    Job counts cover the worker's SQLite history across restarts, with no
    time window or record limit. Removing history reduces these counts.

    Returns:
        Result: Validated monitoring snapshot, including total jobs and
            counts by status under ``jobs``. Failed jobs are counted
            separately from completed jobs.
    """
    stats_data = {
        "name": self.name,
        "status": "active" if not self.exit_event.is_set() else "stopping",
        "process": self.monitoring.process_stats(),
        "messaging": self.monitoring.messaging_stats(),
        "service": self.service.decode("utf-8"),
        "broker": self.broker,
        "reconnects": self.monitoring.reconnects,
        "outbound_queue_depth": self.outbound_queue.qsize(),
        "running_jobs": len(self.running_jobs),
        "jobs": self.db.jobs_stats(),
        "max_concurrent_jobs": self.max_concurrent_jobs,
        "watchdog_runs": self.watchdog.runs,
        "keepalives_sent": self.keepaliver.keepalives_send,
        "keepalives_received": self.keepaliver.keepalives_received,
    }
    stats_data.update(self.watchdog.get_stats())
    stats = self.monitoring_model(
        **stats_data,
    )
    return Result(result=stats.model_dump(mode="json"))

get_watchdog_configuration() -> Result ¤

Retrieves the current configuration of the watchdog.

Returns:

Name Type Description
Result Result

An object containing the watchdog configuration.

Source code in norfab\core\worker.py
2819
2820
2821
2822
2823
2824
2825
2826
2827
@Task(fastapi={"methods": ["GET"]}, agent={"enabled": False})
def get_watchdog_configuration(self) -> Result:
    """
    Retrieves the current configuration of the watchdog.

    Returns:
        Result: An object containing the watchdog configuration.
    """
    return Result(result=self.watchdog.configuration())

start_threads() -> None ¤

Starts multiple daemon threads required for the worker's operation.

This method initializes and starts the following threads
  • request_thread: Handles posting requests using the _post function.
  • reply_thread: Handles receiving replies using the _get function.
  • event_thread: Handles event processing using the _event function.
  • recv_thread: Handles ZeroMQ send/receive using the zmq_send_recv function.

Each thread is started as a daemon and is provided with the necessary arguments, including queues and events as required.

Returns:

Type Description
None

None

Source code in norfab\core\worker.py
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
def start_threads(self) -> None:
    """
    Starts multiple daemon threads required for the worker's operation.

    This method initializes and starts the following threads:
        - request_thread: Handles posting requests using the _post function.
        - reply_thread: Handles receiving replies using the _get function.
        - event_thread: Handles event processing using the _event function.
        - recv_thread: Handles ZeroMQ send/receive using the zmq_send_recv function.

    Each thread is started as a daemon and is provided with the necessary arguments,
    including queues and events as required.

    Returns:
        None
    """
    # Start threads
    self.request_thread = threading.Thread(
        target=_post,
        daemon=True,
        name=f"{self.name}_post_thread",
        args=(
            self,
            self.post_queue,
            self.destroy_event,
        ),
    )
    self.request_thread.start()
    self.reply_thread = threading.Thread(
        target=_get,
        daemon=True,
        name=f"{self.name}_get_thread",
        args=(self, self.get_queue, self.destroy_event),
    )
    self.reply_thread.start()
    self.event_thread = threading.Thread(
        target=_event,
        daemon=True,
        name=f"{self.name}_event_thread",
        args=(self, self.event_queue, self.destroy_event),
    )
    self.event_thread.start()
    self.put_thread = threading.Thread(
        target=_put,
        daemon=True,
        name=f"{self.name}_put_thread",
        args=(
            self,
            self.put_queue,
            self.destroy_event,
        ),
    )
    self.put_thread.start()
    # start receive thread after other threads
    self.recv_thread = threading.Thread(
        target=zmq_send_recv,
        daemon=True,
        name=f"{self.name}_zmq_send_recv_thread",
        args=(
            self,
            self.destroy_event,
        ),
    )
    self.recv_thread.start()

run_next_job(uuid: str) -> None ¤

Processes the next job from the database.

This method performs the following steps:

  1. Loads job data from the database.
  2. Parses the job data to extract the task name, arguments, keyword arguments, and timeout.
  3. Executes the specified task method on the worker instance with the provided arguments.
  4. Handles any exceptions raised during task execution, logging errors and creating a failed Result object if needed.
  5. Saves the result of the job execution to the database.
  6. Marks the job as completed or failed in the database.
  7. Emits the result_ready event after persistence.

Parameters:

Name Type Description Default
uuid str

The job UUID to process.

required

Raises:

Type Description
TypeError

If the executed task does not return a Result object.

Source code in norfab\core\worker.py
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
def run_next_job(self, uuid: str) -> None:
    """
    Processes the next job from the database.

    This method performs the following steps:

    1. Loads job data from the database.
    2. Parses the job data to extract the task name, arguments, keyword arguments, and timeout.
    3. Executes the specified task method on the worker instance with the provided arguments.
    4. Handles any exceptions raised during task execution, logging errors and creating a failed Result object if needed.
    5. Saves the result of the job execution to the database.
    6. Marks the job as completed or failed in the database.
    7. Emits the result_ready event after persistence.

    Args:
        uuid (str): The job UUID to process.

    Raises:
        TypeError: If the executed task does not return a Result object.
    """
    log.info(f"{self.name} - Processing job request {uuid}")

    # Load job data from database
    job_data = self.db.get_job_info(uuid)
    if not job_data:
        log.error(f"{self.name} - job {uuid} not found in database")
        return

    client_address = job_data["client_address"]
    task = job_data["task"]
    args = job_data["args"]
    kwargs = job_data["kwargs"]
    timeout = job_data["timeout"]

    job = Job(
        worker=self,
        client_address=client_address,
        juuid=uuid,
        task=task,
        timeout=timeout,
        args=copy.deepcopy(args),
        kwargs=copy.deepcopy(kwargs),
        client_input_queue=queue.Queue(maxsize=0),
    )
    self.running_jobs[uuid] = job

    log.debug(
        f"{self.name} - doing task '{task}', timeout: '{timeout}', "
        f"args: '{args}', kwargs: '{kwargs}', client: '{client_address}', "
        f"job uuid: '{uuid}'"
    )
    log.info(f"{self.name} - Starting task '{task}' for job {uuid}")

    # inform client that job started
    job.event(message="starting", status="running")

    # run the actual job
    try:
        task_started = time.ctime()
        result = NORFAB_WORKER_TASKS[task]["function"](
            self, *args, job=job, **kwargs
        )
        task_completed = time.ctime()
        if not isinstance(result, Result):
            raise TypeError(
                f"{self.name} - task '{task}' did not return Result object, "
                f"args: '{args}', kwargs: '{kwargs}', client: '{client_address}', "
                f"job uuid: '{uuid}'; task returned '{type(result)}'"
            )
        result.task = result.task or f"{self.name}:{task}"
        result.status = result.status or "completed"
        result.juuid = result.juuid or uuid
        result.service = self.service.decode("utf-8")
        job_failed = False
    except Exception as e:
        task_completed = time.ctime()
        result = Result(
            task=f"{self.name}:{task}",
            errors=[traceback.format_exc()],
            messages=[f"Worker experienced error: '{e}'"],
            status="timeout" if job.is_timed_out() else "error",
            failed=True,
            juuid=uuid,
        )
        log.error(
            f"{self.name} - worker experienced error:\n{traceback.format_exc()}"
        )
        job_failed = True

    result.task_started = task_started
    result.task_completed = task_completed

    # Prepare result data for database storage as JSON-serializable dict
    result_data = {
        "client_address": client_address,
        "uuid": uuid,
        "status_code": "200",
        "result": {self.name: result.model_dump()},
        "worker": self.name,
        "service": self.service.decode("utf-8"),
    }

    # Save job result to database
    if job_failed:
        self.db.fail_job(uuid, result_data)
        log.error(f"{self.name} - Task '{task}' failed for job {uuid}")
    else:
        self.db.complete_job(uuid, result_data)
        log.info(f"{self.name} - Completed task '{task}' for job {uuid}")

    # remove job from running jobs
    _ = self.running_jobs.pop(uuid)

    # inform client that job completed
    job.event(message="completed", status="completed", event_type="result_ready")

work() -> None ¤

Executes the main worker loop, managing job execution using a thread pool.

This method starts necessary background threads, then enters a loop where it:

  • Queries the database for the next pending job.
  • Atomically marks the job as started in the database.
  • Submits the job to a thread pool executor for concurrent processing.
  • Waits briefly if no pending jobs are found.
  • Continues until either the exit or destroy event is set.

Upon exit, performs cleanup by calling the destroy method with a status message.

Source code in norfab\core\worker.py
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
def work(self) -> None:
    """
    Executes the main worker loop, managing job execution using a thread pool.

    This method starts necessary background threads, then enters a loop where it:

    - Queries the database for the next pending job.
    - Atomically marks the job as started in the database.
    - Submits the job to a thread pool executor for concurrent processing.
    - Waits briefly if no pending jobs are found.
    - Continues until either the exit or destroy event is set.

    Upon exit, performs cleanup by calling the `destroy` method with a status message.
    """

    self.start_threads()

    # start job threads and submit jobs in an infinite loop
    with concurrent.futures.ThreadPoolExecutor(
        max_workers=self.max_concurrent_jobs,
        thread_name_prefix=f"{self.name}-job-thread",
    ) as executor:
        while not self.exit_event.is_set() and not self.destroy_event.is_set():
            # Get next pending job from database
            job_info = self.db.get_next_pending_job()

            if job_info is None:
                # Sleep until a POST adds work, while retaining a bounded
                # wait so shutdown events are observed promptly.
                self.pending_job_event.wait(timeout=1)
                self.pending_job_event.clear()
                continue

            uuid, received_timestamp = job_info
            log.debug(f"{self.name} - submitting job {uuid} to executor")

            # Submit the job to workers
            executor.submit(self.run_next_job, uuid)

    # make sure to clean up
    self.destroy(
        f"{self.name} - exit event is set '{self.exit_event.is_set()}', "
        f"destroy event is set '{self.destroy_event.is_set()}'"
    )

zmq_send_recv(worker: object, destroy_event: threading.Event) -> None ¤

ZeroMQ send/receive thread.

This function owns the worker's broker socket. Other threads submit prepared messages to the outbound queue instead of touching the socket directly. It drains outbound messages, sends due keepalives, polls the socket, and processes received messages.

Parameters:

Name Type Description Default
worker Worker

The worker instance that contains the broker socket and queues.

required
destroy_event Event

An event to signal the thread to stop.

required
Commands
  • NFP.POST: Places the message into the post_queue.
  • NFP.DELETE: Places the message into the delete_queue.
  • NFP.GET: Places the message into the get_queue.
  • NFP.KEEPALIVE: Processes a keepalive heartbeat.
  • NFP.DISCONNECT: Attempts to reconnect to the broker.
  • Other: Logs an invalid input message.
Source code in norfab\core\worker.py
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
def zmq_send_recv(worker: object, destroy_event: threading.Event) -> None:
    """
    ZeroMQ send/receive thread.

    This function owns the worker's broker socket. Other threads submit prepared
    messages to the outbound queue instead of touching the socket directly.
    It drains outbound messages, sends due keepalives, polls the socket, and
    processes received messages.

    Args:
        worker (Worker): The worker instance that contains the broker socket and queues.
        destroy_event (threading.Event): An event to signal the thread to stop.

    Commands:
        - NFP.POST: Places the message into the post_queue.
        - NFP.DELETE: Places the message into the delete_queue.
        - NFP.GET: Places the message into the get_queue.
        - NFP.KEEPALIVE: Processes a keepalive heartbeat.
        - NFP.DISCONNECT: Attempts to reconnect to the broker.
        - Other: Logs an invalid input message.
    """
    while not destroy_event.is_set():
        for _ in range(NFP.ZMQ_SEND_RECV_DRAIN_LIMIT):
            try:
                outbound = worker.outbound_queue.get_nowait()
            except queue.Empty:
                break
            try:
                if not worker.destroy_event.is_set():
                    worker.broker_socket.send_multipart(outbound)
                    worker.monitoring.record_sent()
            except Exception as e:
                worker.monitoring.record_send_failure()
                log.error(
                    f"{worker.name} - failed to send queued message to broker, "
                    f"error '{e}'",
                    exc_info=True,
                )

        if worker.keepaliver and worker.keepaliver.due():
            try:
                if not worker.destroy_event.is_set():
                    worker.broker_socket.send_multipart(
                        worker.keepaliver.make_message()
                    )
                    worker.monitoring.record_sent()
            except Exception as e:
                worker.monitoring.record_send_failure()
                log.error(
                    f"{worker.name} - failed to send keepalive to broker, error '{e}'"
                )

        msg = None
        try:
            # Wait until the next heartbeat deadline, unless messages are queued.
            heartbeat_deadline = min(
                worker.keepaliver.keepalive_at, worker.keepaliver.holdtime
            )
            timeout = max(1, int((heartbeat_deadline - time.time()) * 1000))
            if not worker.outbound_queue.empty():
                timeout = 0
            items = dict(worker.poller.poll(timeout))

            # Clear notifications; queued messages are sent at the top of the loop.
            if items.get(worker.wakeup_reader.fileno(), 0) & zmq.POLLIN:
                try:
                    while worker.wakeup_reader.recv(4096):
                        pass
                except BlockingIOError:
                    pass
            if items.get(worker.broker_socket, 0) & zmq.POLLIN:
                try:
                    msg = worker.broker_socket.recv_multipart(zmq.NOBLOCK)
                except zmq.Again:
                    # Readiness can become stale; resume polling instead of blocking.
                    pass
        except KeyboardInterrupt:
            break  # Interrupted

        if msg is not None:
            worker.monitoring.record_received()
            log.debug(f"{worker.name} - received '{msg}'")
            if len(msg) < 3:
                worker.monitoring.record_receive_failure()
                log.error(f"{worker.name} - received malformed message: {msg}")
                continue
            empty = msg.pop(0)  # noqa
            header = msg.pop(0)
            command = msg.pop(0)

            if command == NFP.POST:
                worker.post_queue.put(msg)
            elif command == NFP.DELETE:
                worker.delete_queue.put(msg)
            elif command == NFP.GET:
                worker.get_queue.put(msg)
            elif command == NFP.PUT:
                worker.put_queue.put(msg)
            elif command == NFP.STREAM:
                job = worker.running_jobs.get(msg[2].decode())
                if job and msg[0].decode() == job.client_address:
                    job.binary_input_queue.put((b"200", msg[3]))
            elif command == NFP.KEEPALIVE:
                worker.keepaliver.received_heartbeat([header] + msg)
            elif command == NFP.DISCONNECT:
                ready_msg = worker.reconnect_to_broker(queue_ready=False)
                if ready_msg and not worker.destroy_event.is_set():
                    try:
                        worker.broker_socket.send_multipart(ready_msg)
                        worker.monitoring.record_sent()
                    except Exception as e:
                        worker.monitoring.record_send_failure()
                        log.error(
                            f"{worker.name} - failed to send ready to broker, "
                            f"error '{e}'"
                        )
            else:
                log.debug(
                    f"{worker.name} - invalid input, header '{header}', command '{command}', message '{msg}'"
                )

        if not worker.keepaliver.is_alive():
            log.warning(f"{worker.name} - '{worker.broker}' broker keepalive expired")
            if not worker.destroy_event.is_set():
                disconnect_msg = worker.build_message.worker_to_broker_disconnect(
                    service=worker.service
                )
                try:
                    worker.broker_socket.send_multipart(disconnect_msg)
                    worker.monitoring.record_sent()
                except Exception as e:
                    worker.monitoring.record_send_failure()
                    log.error(
                        f"{worker.name} - failed to send disconnect to broker, "
                        f"error '{e}'"
                    )
            ready_msg = worker.reconnect_to_broker(queue_ready=False)
            if ready_msg and not worker.destroy_event.is_set():
                try:
                    worker.broker_socket.send_multipart(ready_msg)
                    worker.monitoring.record_sent()
                except Exception as e:
                    worker.monitoring.record_send_failure()
                    log.error(
                        f"{worker.name} - failed to send ready to broker, error '{e}'"
                    )