diff --git a/packages/core/src/openbim/IDSSpecifications/src/Specification.ts b/packages/core/src/openbim/IDSSpecifications/src/Specification.ts index 96ce69af6..02211c714 100644 --- a/packages/core/src/openbim/IDSSpecifications/src/Specification.ts +++ b/packages/core/src/openbim/IDSSpecifications/src/Specification.ts @@ -70,13 +70,18 @@ export class IDSSpecification implements IDSSpecificationData { await Promise.all(applicabilityPromises); - // Test applicable elements against requirements - const requirementPromises = []; - for (const requirement of this.requirements) { - requirementPromises.push(requirement.test(entities, result, config)); + // Test applicable elements against requirements. They test the same + // items, so they share one fetch of each kind of item data. + IDSFacet.startSharedItemsData(entities); + try { + const requirementPromises = []; + for (const requirement of this.requirements) { + requirementPromises.push(requirement.test(entities, result, config)); + } + await Promise.all(requirementPromises); + } finally { + IDSFacet.endSharedItemsData(entities); } - - await Promise.all(requirementPromises); return result; } diff --git a/packages/core/src/openbim/IDSSpecifications/src/facets/Attribute.ts b/packages/core/src/openbim/IDSSpecifications/src/facets/Attribute.ts index 841753f38..39d9f4d4d 100644 --- a/packages/core/src/openbim/IDSSpecifications/src/facets/Attribute.ts +++ b/packages/core/src/openbim/IDSSpecifications/src/facets/Attribute.ts @@ -80,10 +80,15 @@ export class IDSAttribute extends IDSFacet { config: { skipIfFails: boolean } = { skipIfFails: true }, ) { const fragments = this._components.get(FragmentsManager); - for (const [modelId, localIds] of Object.entries(items)) { + for (const modelId of Object.keys(items)) { const model = fragments.list.get(modelId); if (!model) continue; - const data = await model.getItemsData([...localIds]); + const data = await this.getSharedItemsData( + items, + modelId, + model, + "attributes", + ); for (const item of data) { const checks = this.getItemChecks( collector, diff --git a/packages/core/src/openbim/IDSSpecifications/src/facets/Entity.ts b/packages/core/src/openbim/IDSSpecifications/src/facets/Entity.ts index a4a27d159..1033d02e4 100644 --- a/packages/core/src/openbim/IDSSpecifications/src/facets/Entity.ts +++ b/packages/core/src/openbim/IDSSpecifications/src/facets/Entity.ts @@ -109,11 +109,16 @@ export class IDSEntity extends IDSFacet { config: { skipIfFails: boolean }, ) { const fragments = this._components.get(FragmentsManager); - for (const [modelId, localIds] of Object.entries(items)) { + for (const modelId of Object.keys(items)) { const model = fragments.list.get(modelId); if (!model) continue; - const data = await model.getItemsData([...localIds]); + const data = await this.getSharedItemsData( + items, + modelId, + model, + "attributes", + ); for (const item of data) { if (!("value" in item._category)) continue; const checks = this.getItemChecks( diff --git a/packages/core/src/openbim/IDSSpecifications/src/facets/Facet.ts b/packages/core/src/openbim/IDSSpecifications/src/facets/Facet.ts index c4b7f43d6..6abfe7ac8 100644 --- a/packages/core/src/openbim/IDSSpecifications/src/facets/Facet.ts +++ b/packages/core/src/openbim/IDSSpecifications/src/facets/Facet.ts @@ -12,9 +12,57 @@ import { } from "../types"; import { ModelIdDataMap, ModelIdMap } from "../../../../fragments"; +/** + * Item data fetched once per specification run and shared by its + * requirements, keyed by the applicable items of that run. Each + * `getItemsData` call has a large fixed cost in the fragments worker, and + * every requirement of a specification tests the same items. + */ +const sharedItemsData = new WeakMap< + ModelIdMap, + Map> +>(); + export abstract class IDSFacet { abstract facetType: IDSFacetType; + /** + * Lets the facets tested on `items` share their item data until + * {@link endSharedItemsData} is called. Used by `IDSSpecification.test`. + */ + static startSharedItemsData(items: ModelIdMap) { + sharedItemsData.set(items, new Map()); + } + + static endSharedItemsData(items: ModelIdMap) { + sharedItemsData.delete(items); + } + + /** + * `model.getItemsData` for the items of `modelId`, shared with the other + * requirements of the same specification run when one is in progress. + * Requests with the same `key` must use the same `config`, and callers + * must not modify the returned data. + */ + protected getSharedItemsData( + items: ModelIdMap, + modelId: string, + model: FRAGS.FragmentsModel, + key: string, + config?: Parameters[1], + ) { + const fetch = () => model.getItemsData([...items[modelId]], config); + const shared = sharedItemsData.get(items); + if (!shared) return fetch(); + const fullKey = `${key}:${modelId}`; + let data = shared.get(fullKey); + if (!data) { + data = fetch(); + shared.set(fullKey, data); + } + return data; + } + // Used when the facet is a requirement // On IDSEntity is always required cardinality: IDSSimpleCardinality | IDSConditionalCardinaltiy = "required"; diff --git a/packages/core/src/openbim/IDSSpecifications/src/facets/Property.ts b/packages/core/src/openbim/IDSSpecifications/src/facets/Property.ts index c15b9e210..6c9b793e6 100644 --- a/packages/core/src/openbim/IDSSpecifications/src/facets/Property.ts +++ b/packages/core/src/openbim/IDSSpecifications/src/facets/Property.ts @@ -286,20 +286,32 @@ export class IDSProperty extends IDSFacet { config: { skipIfFails: boolean } = { skipIfFails: true }, ) { const fragments = this._components.get(FragmentsManager); - for (const [modelId, localIds] of Object.entries(items)) { + for (const modelId of Object.keys(items)) { const model = fragments.list.get(modelId); if (!model) continue; - const data = await model.getItemsData([...localIds], { - relations: { - IsDefinedBy: { attributes: true, relations: true }, - IsTypedBy: { attributes: true, relations: false }, - HasPropertySets: { attributes: true, relations: true }, - // Both spellings on purpose: old .frag files store the pre-3.4 - // relation name "DefinesOcurrence" (see getEntities above). - DefinesOccurrence: { attributes: false, relations: false }, - DefinesOcurrence: { attributes: false, relations: false }, + const data = await this.getSharedItemsData( + items, + modelId, + model, + "psets", + { + relations: { + IsDefinedBy: { attributes: true, relations: true }, + IsTypedBy: { attributes: true, relations: false }, + HasPropertySets: { attributes: true, relations: true }, + // Both spellings on purpose: old .frag files store the pre-3.4 + // relation name "DefinesOcurrence" (see getEntities above). + DefinesOccurrence: { attributes: false, relations: false }, + DefinesOcurrence: { attributes: false, relations: false }, + // A relation without its own entry here takes the config of the + // relation it was reached through. Without these, the type + // reached through IsDefinedBy would bring along every other + // instance of that type, with all their property sets. + ObjectTypeOf: { attributes: false, relations: false }, + Types: { attributes: false, relations: false }, + }, }, - }); + ); for (const item of data) { const checks = this.getItemChecks( @@ -484,22 +496,26 @@ export class IDSProperty extends IDSFacet { return set.Name.value === definitionName; }); - if (typeSet) { - mergedTypeSets.add(typeSet); - if ( - Array.isArray(typeSet.HasProperties) && - Array.isArray(definition.HasProperties) - ) { - for (const prop of typeSet.HasProperties) { - if (!(prop.Name && "value" in prop.Name)) continue; - const name = prop.Name.value; - const existingProp = definition.HasProperties.find((p) => { - if (!(p.Name && "value" in p.Name)) return false; - return p.Name.value === name; - }); - if (!existingProp) definition.HasProperties.push(prop); - } + if (typeSet) mergedTypeSets.add(typeSet); + if ( + typeSet && + Array.isArray(typeSet.HasProperties) && + Array.isArray(definition.HasProperties) + ) { + // A copy: the item data is shared with the specification's other + // requirements, so it must not be modified. + const properties = [...definition.HasProperties]; + for (const prop of typeSet.HasProperties) { + if (!(prop.Name && "value" in prop.Name)) continue; + const name = prop.Name.value; + const existingProp = properties.find((p) => { + if (!(p.Name && "value" in p.Name)) return false; + return p.Name.value === name; + }); + if (!existingProp) properties.push(prop); } + sets.push({ ...definition, HasProperties: properties }); + continue; } sets.push(definition); diff --git a/packages/core/src/openbim/IDSSpecifications/src/specification-items-data.test.ts b/packages/core/src/openbim/IDSSpecifications/src/specification-items-data.test.ts new file mode 100644 index 000000000..558c5b872 --- /dev/null +++ b/packages/core/src/openbim/IDSSpecifications/src/specification-items-data.test.ts @@ -0,0 +1,154 @@ +import * as FRAGS from "@thatopen/fragments"; +import * as fs from "fs"; +import * as path from "path"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import type { Components } from "../../../index"; +import { loadSourceBundle } from "../../../../tests/source-bundle"; + +// Needs the real `Components`: see `loadSourceBundle`. +const OBC = await loadSourceBundle(); + +const MODEL_ID = "type-psets"; + +// `tests/fixtures/type-psets.ifc` (see facets/property.test.ts): six walls, +// some of which inherit Pset_WallCommon from their type. +const WALLS = [40, 41, 42, 43, 45, 46]; + +const convert = async () => { + const importer = new FRAGS.IfcImporter(); + const root = path.resolve(__dirname, "../../../.."); + importer.wasm = { + path: `${path.resolve(root, "../../node_modules/web-ifc")}/`, + absolute: true, + }; + const ifc = fs.readFileSync( + path.join(root, "tests", "fixtures", "type-psets.ifc"), + ); + const bytes = await importer.process({ + bytes: new Uint8Array(ifc), + raw: true, + }); + return new FRAGS.SingleThreadedFragmentsModel(MODEL_ID, bytes, true); +}; + +describe("IDSSpecification item data", () => { + let components: Components; + let model: FRAGS.SingleThreadedFragmentsModel; + + beforeAll(async () => { + model = await convert(); + components = new OBC.Components(); + const fragments = components.get(OBC.FragmentsManager); + vi.spyOn(fragments, "list", "get").mockReturnValue( + new Map([[MODEL_ID, model]]) as never, + ); + }, 60_000); + + afterAll(() => { + vi.restoreAllMocks(); + components?.dispose(); + model?.dispose(); + }); + + const requirements = () => { + const property = (baseName: string, value?: boolean) => { + const facet = new OBC.IDSProperty( + components, + { type: "simple", parameter: "Pset_WallCommon" }, + { type: "simple", parameter: baseName }, + ); + if (value !== undefined) { + facet.value = { type: "simple", parameter: value }; + } + return facet; + }; + const name = new OBC.IDSAttribute(components, { + type: "simple", + parameter: "Name", + }); + const tag = new OBC.IDSAttribute(components, { + type: "simple", + parameter: "Tag", + }); + tag.cardinality = "optional"; + return [ + property("IsExternal", true), + property("IsExternal"), + property("LoadBearing"), + name, + tag, + ]; + }; + + const specification = () => { + const spec = components + .get(OBC.IDSSpecifications) + .create("Walls", ["IFC4"]); + spec.applicability.add( + new OBC.IDSEntity(components, { type: "simple", parameter: "IFCWALL" }), + ); + spec.requirements.add(...requirements()); + return spec; + }; + + const run = () => + specification().test([new RegExp(MODEL_ID)], { skipIfFails: false }); + + // Requirements run concurrently, so the order of an item's checks varies. + const summary = (result: Awaited>) => + [...result.get(MODEL_ID)!.entries()] + .sort(([a], [b]) => a - b) + .map(([id, item]) => [ + id, + item.checks.map((check) => `${check.facetType}:${check.pass}`).sort(), + ]); + + it("fetches the applicable items once per kind of data, not once per requirement", async () => { + const getItemsData = vi.spyOn(model, "getItemsData"); + await run(); + const fetchesOfApplicableItems = getItemsData.mock.calls.filter( + ([ids]) => ids.length === WALLS.length, + ); + getItemsData.mockRestore(); + + // One with the property set relations, one with the attributes only. + expect(fetchesOfApplicableItems).toHaveLength(2); + }); + + it("does not fetch the other instances of an element's type", async () => { + const getItemsData = vi.spyOn(model, "getItemsData"); + await run(); + const fetched = await Promise.all( + getItemsData.mock.results.map((result) => result.value), + ); + getItemsData.mockRestore(); + + // Walls 40, 41, 45 and 46 share type #52; the property facet only needs + // the type's own property sets, not the walls the type is used by. + const reachedThroughType = (data: unknown): boolean => + Array.isArray(data) + ? data.some(reachedThroughType) + : typeof data === "object" && + data !== null && + Object.entries(data).some( + ([key, value]) => + key === "ObjectTypeOf" || reachedThroughType(value), + ); + expect(reachedThroughType(fetched)).toBe(false); + }); + + it("gives the same results as testing each requirement on its own", async () => { + const shared = summary(await run()); + + const separate: Awaited> = new FRAGS.DataMap(); + for (const requirement of requirements()) { + await requirement.test({ [MODEL_ID]: new Set(WALLS) }, separate, { + skipIfFails: false, + }); + } + + expect(shared).toEqual(summary(separate)); + // And again: the shared data is not modified by a run. + expect(summary(await run())).toEqual(shared); + }); +});