flync.sdk¶
This page is a full reference of the SDK for developers and contributors to FLYNC.
FLYNC Workspace¶
- class FLYNCWorkspace(name: str, workspace_path: PathType = '', configuration: WorkspaceConfiguration | None = None)¶
Bases:
_WorkspaceSavingWorkspace class managing documents, objects, and diagnostics.
This class provides methods to ingest documents, run analysis, and expose semantic and source APIs for use by the SDK and language server.
- Attributes:
name (str): Name of the workspace.
configuration (WorkspaceConfiguration): Configuration object for workspace behavior.
documents (Dict[str, Document]): Mapping of document URIs to Document objects.
documents_diags (Dict[str, list[ErrorDetails]]): Validation errors indexed by document URI.
objects (Dict[ObjectId, SemanticObject]): Semantic objects indexed by ObjectId.
sources (Dict[ObjectId, SourceRef]): Source references indexed by ObjectId.
flync_model (FLYNCModel | FLYNCBaseModel | None): The root FLYNC model instance, if loaded.
workspace_root (Path | None): Absolute path to the workspace root directory.
- classmethod load_model(flync_model: FLYNCModel, workspace_name: str | None = 'generated_workspace', file_path: PathType = '', workspace_config: WorkspaceConfiguration | None = None) FLYNCWorkspace¶
loads a workspace object from a FLYNC Object.
- Args:
flync_model (str): the FLYNC object from which the workspace will be created.
workspace_name (str): The name of the workspace.
file_path (str | Path): The path of the workspace files.
Returns: FLYNCWorkspace
- classmethod safe_load_workspace(workspace_name: str, workspace_path: PathType, workspace_config: WorkspaceConfiguration | None = None) FLYNCWorkspace¶
loads a workspace object from a location of the Yaml Configuration.
In case this fails, the workspace will still be created, but with an empty model.
- Args:
workspace_name (str): The name of the workspace.
workspace_path (str | Path): The path of the workspace files.
Returns: FLYNCWorkspace
- classmethod load_workspace(workspace_name: str, workspace_path: PathType, workspace_config: WorkspaceConfiguration | None = None) FLYNCWorkspace¶
loads a workspace object from a location of the Yaml Configuration.
- Args:
workspace_name (str): The name of the workspace.
workspace_path (str | Path): The path of the workspace files.
Returns: FLYNCWorkspace
- add_list_item_object_path(item_name, current_object_paths, idx)¶
Build the object path(s) for a single list item.
Depending on
list_objects_mode, the item may be registered under its numeric index, its name, or both:INDEX: appends the zero-based integer index as a path segment.NAME: appendsitem_nameas an additional path segment when the name is non-empty. For external (folder-based) lists the name comes from the file/directory stem; for inline lists it comes from the model’snameattribute.
Both flags are active by default, so a list item is accessible under two IDs simultaneously (e.g.
controllers.0andcontrollers.my_ctrl).- Args:
item_name (str | None): Name of the list item, or
Noneempty string when the item has no name. current_object_paths (list[str]): Parent path(s) to extend. idx (int): Zero-based position of the item in the list.- Returns:
list[str]: New list of object paths for this item.
- document_id_from_path(doc_path: str) str¶
Return the workspace-relative string identifier for a document path.
- Args:
doc_path (str): An absolute path to a document file.
- Returns:
str: The path relative to the workspace root, as a string.
- fill_path_from_object(model_object: FLYNCBaseModel, object_path: str) str¶
Replace placeholder segments in an object path with concrete keys.
Traverses the workspace’s root model following
object_path, substituting[]with the actual list index and{}with the actual dict key whenmodel_objectis found.- Args:
model_object (FLYNCBaseModel): The model instance to locate. object_path (str): Dot-separated path containing
[]or{}placeholders.- Returns:
str: The resolved dot-separated path with concrete index/key values.
- find_path_from_field(object_id: ObjectId, refs: list[ObjectId], semantic_obj: SemanticObject, field: str, info: FieldInfo)¶
Resolve the concrete ObjectId path for a field and append it to refs.
Tries to build the path as <semantic_obj.id>.<field>, falling back to <semantic_obj.id>.<info.alias> when the first candidate is not present in the workspace. Raises if neither candidate exists.
- Args:
- object_id (ObjectId):
The id of the target object being referenced (used in the error message when the path cannot be resolved).
- refs (list[ObjectId]):
Accumulator list to which the resolved path is appended.
- semantic_obj (SemanticObject):
The semantic object that owns the field being inspected.
- field (str):
The field name on semantic_obj’s model.
- info:
The Pydantic FieldInfo for the field, used to access the field alias as a fallback path segment.
- Raises:
- ValueError:
If neither the field name nor its alias resolves to a known object in the workspace.
- generate_configs(uri: PathType | None = None)¶
Save the workspace to the given path.
Creates the output directory (if it does not exist) and writes a simple representation of the workspace. If a FLYNCModel has been loaded via
load_flync_model, it attempts to serialize the model to JSON.- Args:
uri (str | Path | None): Optional argument to save specific file instead of the entire workspace.
Returns: None
- get_child_ids(id: ObjectId) list[str]¶
Return the immediate child ObjectId strings of a given object.
Backed by the
_children_by_parentindex built during object mapping, so this is an O(1) lookup rather than a full scan of the workspace.- Args:
id (ObjectId): Identifier of the parent object.
- Returns:
list[str]: Immediate child id strings (empty if none / not mapped).
- get_definition(object_id: ObjectId, field_name: str) ObjectId | None¶
Resolve and return definition identifiers for a given field reference.
- Args:
- object_id (ObjectId):
Identifier of the semantic object.
- field_name (str)
The field name of referencing object
- Returns:
- ObjectId
A list of object identifiers that match the resolved reference criteria. The list may be empty if no definitions are found or if the field has no valid reference metadata.
- get_metadata(id: ObjectId) ObjectMetadata¶
Retrieve metadata about a semantic object without exposing the full model.
Provides type information, field details, relationships, and source location. The model itself is stored privately and not exposed in serialization.
- Args:
- id (ObjectId):
Identifier of the semantic object.
- Returns:
- ObjectMetadata:
Metadata object with type, fields, annotations, parents, children, and source.
- Raises:
- KeyError:
If the object does not exist in the workspace.
- get_object(id: ObjectId) SemanticObject¶
Retrieve a semantic object by its ObjectId.
- Args:
- id (ObjectId):
Identifier of the semantic object.
- Returns:
- SemanticObject:
The requested semantic object.
- get_references_of(object_id: ObjectId) list[ObjectId]¶
Return all ObjectIds that reference the given object.
Iterates over every semantic object in the workspace and checks whether any of its fields are defined by the same model as the target object. For each matching field, the concrete path to that field is collected via find_path_from_field.
- Args:
- object_id (ObjectId):
The id of the object whose references should be found.
- Returns:
- list[ObjectId]:
A list of ObjectIds representing all fields across the workspace that reference the given object.
- get_semantic_object_from_model(model: FLYNCBaseModel) SemanticObject | None¶
Find and return the first semantic object that corresponds to a validated Flync object.
This method maintains backward compatibility by returning only the first result.
- Args:
- model (FLYNCBaseModel):
Validated Flync model.
- Returns:
- SemanticObject | None:
First semantic object that corresponds to Flync object, or None if not found.
- get_semantic_objects_from_model(model: FLYNCBaseModel) list[SemanticObject]¶
Find and return all semantic objects that correspond to a validated Flync object.
A single model instance may be registered under multiple ObjectIds (e.g., a list item indexed by both numeric position and name).
- Args:
- model (FLYNCBaseModel):
Validated Flync model.
- Returns:
- list[SemanticObject]:
List of semantic objects that correspond to the Flync object. Empty if none found.
- get_semantic_objects_ids_from_model(model: FLYNCBaseModel) list[ObjectId]¶
Find and return ObjectIds for all semantic objects that correspond to a model.
A single model instance may be registered under multiple ObjectIds (e.g., a list item indexed by both numeric position and name).
- Args:
- model (FLYNCBaseModel):
Validated Flync model.
- Returns:
- list[ObjectId]:
List of ObjectIds that correspond to the Flync object. Empty if none found.
- get_source(id: ObjectId) SourceRef¶
Retrieve the source reference for a given ObjectId.
- Args:
- id (ObjectId):
Identifier of the object.
- Returns:
- SourceRef:
The source reference associated with the object.
- has_object(id: ObjectId) bool¶
Checks if a specific key exists within a dictionary of objects.
- Args:
- id (ObjectId):
Identifier of the semantic object.
- Returns:
- bool:
True if the key is found, False otherwise.
- is_flync_file(path: PathType)¶
Return whether a path has a recognised FLYNC file extension.
- Args:
path (PathType): The path to check.
- Returns:
bool:
Trueif the path’s combined suffixes are inallowed_extensions.
- is_path_supported(path: PathType)¶
Return whether a path is a directory or a recognised FLYNC file.
- Args:
path (PathType): The path to check.
- Returns:
bool:
Trueif the path is a directory or a FLYNC file.
- list_objects() list[ObjectId]¶
Return a list of all ObjectIds present in the workspace.
- Returns:
- list[ObjectId]:
List of object identifiers.
- property load_errors¶
Flattened list of all validation errors across all loaded documents.
- Returns:
list[ErrorDetails]: All per-document errors concatenated into a single list.
- load_flync_model(flync_model: FLYNCBaseModel, file_path: PathType = '')¶
Load a FLYNCModel into the workspace.
This is a placeholder implementation that stores the model for later use.
- name_form_file(file_name: str | Path) str¶
Strip all recognised FLYNC file extensions from a filename.
Iterates over every extension in
allowed_extensionsand removes it as a suffix, leaving the bare stem. If apathlib.Pathis passed, only itsnamecomponent is used.- Args:
file_name (str | Path): The filename or path to strip.
- Returns:
str: The filename with all FLYNC extensions removed (e.g.
"my_ecu.flync.yaml"→"my_ecu").
- static new_object_path(current_path: str, new_object_name: int | str) str¶
Extend a dot-separated object path with a new segment.
- Args:
current_path (str): The existing dot-separated path. new_object_name (int | str): The segment to append.
- Returns:
str: The extended path string.
- objects_at(uri: str, line: int, character: int) list[ObjectId]¶
Return the list of ObjectIds located at the specified position in a document.
- Args:
- uri (str):
Document URI.
- line (int):
1-based line number, consistent with the
Positionvalues stored during YAML parsing.- character (int):
1-based character offset within the line.
- Returns:
- list[ObjectId]:
List of object identifiers at the given position.
- update_document(uri: PathType) list[str]¶
Incrementally reconcile the workspace with a single document that changed on disk.
Three cases are handled in place, all re-validating the affected node’s ancestor spine up to the root while reusing the already-loaded sibling models (so cross-document references, resolved by ancestor validators, stay correct) without a full
load_workspace():changed (known document, still on disk): reload just that node and its subtree.
added (unknown document, now on disk): reload the nearest existing ancestor, whose directory scan picks up the new file.
removed (known document, gone from disk): reload the parent, whose scan drops the file.
New or removed items directly under the root, and any change that breaks a root-resolved reference, fall back to
_revalidate_all()(a full re-validation from the cached ASTs, no disk re-read). An unexpected failure falls back to a from-disk_reset_and_reload().- Args:
uri (PathType): Path of the affected document, absolute or workspace-relative.
- Returns:
list[str]: The ids of every document whose model or diagnostics were recomputed.
- update_objects_path(current_paths: list[str], new_object_name: str) list[str]¶
Extend every path in a list with a new segment.
- Args:
current_paths (list[str]): Existing dot-separated paths. new_object_name (str): The segment to append to each path.
- Returns:
list[str]: New list of extended path strings.
Configuration module for FLYNC SDK.
Provides WorkspaceConfiguration and ListObjectsMode, which control how a
FLYNCWorkspace is loaded, validated, and serialized.
- class ListObjectsMode(*values)¶
Bases:
IntFlagFlags controlling how list items are keyed in the workspace object map.
Flags can be combined with
|. The default isINDEX | NAME.- Attributes:
INDEX: Register each list item under its zero-based integer index (e.g.
controllers.0). NAME: Register each list item under its name — the file/directory stem for folder-based lists, or the model’snameattribute for inline YAML lists. Items without a name are skipped.
- class WorkspaceConfiguration(flync_file_extension: str = '.flync.yaml', allowed_extensions: set[str] = <factory>, exclude_unset: bool = True, root_model: Type[FLYNCBaseModel] = <class 'flync.model.flync_model.FLYNCModel'>, map_objects: bool = False, list_objects_mode: ListObjectsMode = <ListObjectsMode.INDEX|NAME: 3>)¶
Bases:
objectConfiguration object for the FLYNC SDK workspace.
- Attributes:
flync_file_extension (str): The primary file extension used when writing FLYNC configuration files. Defaults to
".flync.yaml". allowed_extensions (set[str]): Set of file extensions recognized as FLYNC files. Defaults to{".flync.yaml", ".flync.yml"}. exclude_unset (bool): WhenTrue, fields that were not explicitly set on a model are omitted from serialized output. root_model (Type[FLYNCBaseModel]): The root Pydantic model class used to validate workspace contents. map_objects (bool): tells the workspace if it should map all objects in the workspace (reduces performance). list_objects_mode (ListObjectsMode): Controls how objects are keyed when listed. Defaults toINDEX | NAME.
- root_model¶
alias of
FLYNCModel
- classmethod create_from_config(existing_config: WorkspaceConfiguration, **configs) WorkspaceConfiguration¶
Create a new configuration by overriding fields on an existing one.
Converts
existing_configto a dict, appliesconfigson top, then constructs and returns a newWorkspaceConfiguration.- Args:
existing_config (WorkspaceConfiguration): The base configuration to copy from. configs: Field names and new values to override.
- Returns:
WorkspaceConfiguration: A new instance with the overrides applied.
ObjectMetadata¶
Provides lightweight metadata about semantic objects without exposing the full model.
- class ObjectMetadata(semantic_obj: SemanticObject, workspace: FLYNCWorkspace)¶
Bases:
objectMetadata about a semantic object for JSON serialization.
Provides type information, field details, relationships, and source location without exposing the full model data (which can be large).
- Attributes:
id (ObjectId): Identifier of the semantic object. type_name (str): Class name of the model. source (dict): Source file reference {uri, range}.
- property type_name: str¶
Class name of the model.
- property name: str¶
Display name: model’s ‘name’ attribute, or last segment of the ObjectId.
- property parent_id: str | None¶
Parent ObjectId (immediate container), or None if root.
- property child_ids: list[str]¶
Direct child ObjectIds, collapsing SINGLE_FILE wrapper levels.
- property source: dict¶
Source file and location {uri, range}.
- property fields: dict[str, FieldMetadata]¶
Maps reference fields to the ObjectId(s) they resolve to.
Only fields explicitly annotated with
Referenceare treated as references, and each target is resolved through the workspace’s reference machinery (the privatesourceattribute). A field’s target is never inferred from Python object identity: interned scalar values (e.g. a discriminatormode: "base_t1"shared across many ports) would otherwise collide, making a plain scalar masquerade as a reference to every other field that happens to hold the same literal.
- to_dict() dict¶
Serialize metadata to a dictionary (for REST JSON responses).
The model is kept private and not included in the output. Clients should use a separate /data endpoint if they need the full model.
- Returns:
dict: Metadata only, without the model.
Usage Example:
from flync.sdk.workspace.flync_workspace import FLYNCWorkspace
from flync.sdk.workspace.ids import ObjectId
workspace = FLYNCWorkspace.load_workspace("my_ws", "/path/to/workspace")
# Get metadata (lightweight, no full model)
metadata = workspace.get_metadata(ObjectId("ecus.my_ecu"))
print(metadata.type_name) # "ECU"
print(metadata.fields) # {"name": str, "description": str, ...}
print(metadata.parent_id) # "ecus"
print(metadata.child_ids) # ["ecus.my_ecu.controllers", ...]
# Serialize to dict for JSON
metadata_dict = metadata.to_dict()
# Get full model only when needed
semantic_obj = workspace.get_object(ObjectId("ecus.my_ecu"))
model_data = semantic_obj.model.model_dump()
Document¶
- class Document(uri: PathType, text: str, needs_compose: bool)¶
Bases:
objectRepresents a YAML document with parsing capabilities.
- Attributes:
uri (str): The unique identifier for the document.
text (str): The raw YAML content.
ast (Any | None): The parsed abstract syntax tree, or None if not parsed.
compose_ast (Any | None): The composed ruamel.yaml AST used for source-position tracking, or None if not parsed. needs_compose (bool): Whether to produce a composed AST.
- parse()¶
Parse the YAML text into an abstract syntax tree.
Sets
astviayaml.loadandcompose_astviayaml.compose, both derived fromtext.Returns: None
- update_text(text: str)¶
Update the document’s text and re-parse it.
- Args:
text (str): The new YAML content.
Returns: None
- assign_ast(ast, compose_ast)¶
Assign parsed YAML structures to the Document instance.
- Args:
ast: Parsed YAML object tree. compose_ast: Composed YAML node tree (optional, used for object maps).
- classmethod normalize_uri(uri: PathType, ws_root: Path | None) str¶
Normalize a file URI relative to the workspace root.
- Args:
uri (Path): File path to normalize. ws_root (Path): Workspace root path.
- Returns:
str: Normalized URI as POSIX-style string.
Utils & Helpers¶
Field utility helpers for the FLYNC SDK.
Provides functions for extracting metadata and display names from Pydantic model fields.
- get_metadata(meta: Iterable[object], cls: type[T]) T | None¶
Return the first metadata object of the specified type.
- Args:
meta: An iterable of metadata objects. cls: The class type to search for.
- Returns:
An instance of cls if found; otherwise, None.
- get_name(named_object: T, attr_name: str, fallback_name: str | None = None) str¶
Retrieve a display name for an object.
Looks up
attr_nameonnamed_object. Falls back tofallback_nameif the attribute is absent or falsy, and finally to the class name if that is also absent.- Args:
named_object: The object whose name should be retrieved. attr_name: The attribute name to look up on the object. fallback_name: Optional fallback value when the attribute is missing.
- Returns:
The resolved display name string.
- get_field_name_from_alias(model: type[BaseModel], alias: str)¶
Resolve a field name from its alias in a Pydantic model.
- Args:
model (type[BaseModel]): The Pydantic model class to inspect. alias (str): The alias of the field to look up.
- Returns:
- str: The actual field name corresponding to the given alias.
If no field with the alias exists, the alias itself is returned.
Generates FLYNC model skeletons for the SDK.
Builds example objects via polyfactory based factories - FLYNCFactory for FLYNC model nodes,
ExternalConnectionFactory for external connections and BASET1Factory for BASE-T1 PHYs.
generate_node() and generate_external_node() create new objects inside a workspace and
dump_flync_workspace() writes a workspace back out.
- safe_issubclass(candidate: object, base) bool¶
Safely determine whether a given object is a subclass of a specified base class.
- is_union(tp) bool¶
Determine whether a given type annotation represents a Union type.
- class Factory¶
Bases:
objectFactory class for managing and generating model-specific factory instances.
- class FLYNCFactory¶
Bases:
ModelFactory[FLYNCBaseModel]Specialized factory class for creating instances of FLYNCBaseModel subclasses.
- classmethod get_provider_map()¶
Map types to callables which accept no arguments and return a random value of the given type.
- Notes:
This method is distinct to allow overriding.
- Returns:
a dictionary mapping types to callables.
- classmethod build(**kwargs)¶
Build an instance of the factory’s __model__
- Parameters:
factory_use_construct – A boolean that determines whether validations will be made when instantiating the model. This is supported only for pydantic models.
kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.
- Returns:
An instance of type T.
- class ExternalConnectionFactory¶
Bases:
FLYNCFactoryFactory for ExternalConnection model.
- classmethod build(**kwargs)¶
Build an instance of the factory’s __model__
- Parameters:
factory_use_construct – A boolean that determines whether validations will be made when instantiating the model. This is supported only for pydantic models.
kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.
- Returns:
An instance of type T.
- class BASET1Factory¶
Bases:
FLYNCFactoryFactory for BASET1 model.
- classmethod build(**kwargs)¶
Build an instance of the factory’s __model__
- Parameters:
factory_use_construct – A boolean that determines whether validations will be made when instantiating the model. This is supported only for pydantic models.
kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.
- Returns:
An instance of type T.
- class ECUFactory¶
Bases:
FLYNCFactoryFactory for ECU model.
- classmethod build(**kwargs)¶
Build an instance of the factory’s __model__
- Parameters:
factory_use_construct – A boolean that determines whether validations will be made when instantiating the model. This is supported only for pydantic models.
kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.
- Returns:
An instance of type T.
- dump_flync_workspace(flync_model: FLYNCModel, output_path: str | Path, workspace_name: str | None, workspace_config: WorkspaceConfiguration | None = None) None¶
Generate a FLYNC workspace from a FLYNCModel object.
- Args:
flync_model (
FLYNCModel): The FLYNC model to generate the workspace from. output_path (str | pathlib.Path): The path where the workspace will be created. workspace_name (str | None): Optional name for the workspace. workspace_config (WorkspaceConfiguration | None): Optional workspace configuration. Uses defaults ifNone.- Returns:
None
- generate_external_node(node: str | type[FLYNCBaseModel], node_path: Path | str, workspace_config: WorkspaceConfiguration | None = None, **override_values)¶
Generate external node.
- generate_node(ws: FLYNCWorkspace, node_paths: list[str] = [], **override_values) bool¶
Build and attach a FLYNC node in the workspace.
Resolves the given path, creates the node using its factory with optional overrides, and attaches it to the workspace or parent.
When the node belongs to a list field on an existing owner model, the node is appended to the owner’s field and the owner is re-serialized.
When the generated node is the root model, the workspace root model is replaced.
- Args:
ws (FLYNCWorkspace): The workspace object in which the node will be generated and attached. node_paths (list[str]): A list of path components identifying the target node location. Each element may be a dot-separated segment (e.g.,
ecus.0) or a plain segment (e.g.,ecus). Defaults to an empty list. override_values: Arbitrary keyword arguments used to override default values when building the node via its factory.- Returns:
bool:
Trueif the node was successfully generated and attached,Falseif the path cannot be resolved or workspace root isNone.