@open-mercato/shared 0.10.1-develop.8212.1.08dada9624 → 0.10.1-develop.8213.1.9d96dc8885
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { sql } from "kysely";
|
|
2
2
|
import { resolveEntityTableName } from "../query/engine.js";
|
|
3
3
|
import { listEntityMetadata } from "./entityMetadata.js";
|
|
4
|
+
import { getTelemetryRuntime } from "../telemetry/runtime.js";
|
|
5
|
+
import { createLogger } from "../logger/index.js";
|
|
6
|
+
const logger = createLogger("shared.recordScope");
|
|
4
7
|
const ORGANIZATION_COLUMN = "organization_id";
|
|
5
8
|
const TENANT_COLUMN = "tenant_id";
|
|
6
9
|
let probedColumnsCache = /* @__PURE__ */ new WeakMap();
|
|
@@ -36,13 +39,21 @@ async function probeScopeColumns(db, table) {
|
|
|
36
39
|
};
|
|
37
40
|
cache.set(table, resolved);
|
|
38
41
|
return resolved;
|
|
39
|
-
} catch {
|
|
42
|
+
} catch (error) {
|
|
43
|
+
try {
|
|
44
|
+
getTelemetryRuntime()?.reportError(error, {
|
|
45
|
+
module: "shared",
|
|
46
|
+
code: "shared.scope_column_probe_failed",
|
|
47
|
+
attributes: { table }
|
|
48
|
+
});
|
|
49
|
+
} catch (telemetryError) {
|
|
50
|
+
logger.warn("Failed to report a scope column probe error", { err: telemetryError });
|
|
51
|
+
}
|
|
40
52
|
return null;
|
|
41
53
|
}
|
|
42
54
|
}
|
|
43
55
|
async function resolveEntityScopeColumns(em, entityType) {
|
|
44
56
|
const table = resolveEntityTableName(em, entityType);
|
|
45
|
-
if (!table) return null;
|
|
46
57
|
const columns = resolveScopeColumnsFromMetadata(em, table) ?? await probeScopeColumns(em.getKysely(), table);
|
|
47
58
|
if (!columns) return null;
|
|
48
59
|
return { table, ...columns };
|
|
@@ -52,7 +63,7 @@ async function loadEntityRecordScope(em, entityType, recordId) {
|
|
|
52
63
|
if (!columns) return null;
|
|
53
64
|
const selected = [columns.organizationColumn, columns.tenantColumn].filter((column) => column !== null);
|
|
54
65
|
if (selected.length === 0) return null;
|
|
55
|
-
const row = await em.getKysely().selectFrom(columns.table).select(selected).where("id", "=", recordId).executeTakeFirst();
|
|
66
|
+
const row = await em.getKysely().selectFrom(columns.table).select(selected.map((column) => sql`${sql.ref(column)}`.as(column))).where("id", "=", recordId).executeTakeFirst();
|
|
56
67
|
if (!row) return null;
|
|
57
68
|
const organizationId = columns.organizationColumn ? row[columns.organizationColumn] : null;
|
|
58
69
|
const tenantId = columns.tenantColumn ? row[columns.tenantColumn] : null;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/db/recordScope.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Kysely } from 'kysely'\nimport { sql } from 'kysely'\nimport { resolveEntityTableName } from '../query/engine'\nimport { listEntityMetadata } from './entityMetadata'\n\nexport type EntityScopeColumns = {\n table: string\n organizationColumn: string | null\n tenantColumn: string | null\n}\n\nexport type EntityRecordScope = {\n organizationId: string | null\n tenantId: string | null\n}\n\ntype ScopeLookupEntityManager = {\n getKysely: <T = unknown>() => Kysely<T>\n getMetadata?: () => unknown\n}\n\ntype ScopePropertyMetadata = { fieldNames?: unknown }\ntype ScopeDatabase = Record<string,
|
|
5
|
-
"mappings": "AACA,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;
|
|
4
|
+
"sourcesContent": ["import type { Kysely } from 'kysely'\nimport { sql } from 'kysely'\nimport { resolveEntityTableName } from '../query/engine'\nimport { listEntityMetadata } from './entityMetadata'\nimport { getTelemetryRuntime } from '../telemetry/runtime'\nimport { createLogger } from '../logger'\n\nconst logger = createLogger('shared.recordScope')\n\nexport type EntityScopeColumns = {\n table: string\n organizationColumn: string | null\n tenantColumn: string | null\n}\n\nexport type EntityRecordScope = {\n organizationId: string | null\n tenantId: string | null\n}\n\ntype ScopeLookupEntityManager = {\n getKysely: <T = unknown>() => Kysely<T>\n getMetadata?: () => unknown\n}\n\ntype ScopePropertyMetadata = { fieldNames?: unknown }\ntype ScopeDatabase = Record<string, {\n id: unknown\n tenant_id?: unknown\n organization_id?: unknown\n}> & {\n 'information_schema.columns': {\n column_name: unknown\n table_name: unknown\n table_schema: unknown\n }\n}\n\nconst ORGANIZATION_COLUMN = 'organization_id'\nconst TENANT_COLUMN = 'tenant_id'\n\nlet probedColumnsCache = new WeakMap<Kysely<ScopeDatabase>, Map<string, { organizationColumn: string | null; tenantColumn: string | null }>>()\n\nfunction readScopeFieldName(property: ScopePropertyMetadata | undefined): string | null {\n const fieldNames = property?.fieldNames\n if (!Array.isArray(fieldNames) || fieldNames.length !== 1) return null\n const [fieldName] = fieldNames\n return typeof fieldName === 'string' && fieldName.length > 0 ? fieldName : null\n}\n\nfunction resolveScopeColumnsFromMetadata(\n em: ScopeLookupEntityManager,\n table: string,\n): { organizationColumn: string | null; tenantColumn: string | null } | null {\n const matches = listEntityMetadata(em).filter((metadata) => metadata.tableName === table)\n if (matches.length !== 1) return null\n const properties = (matches[0].properties ?? {}) as Record<string, ScopePropertyMetadata | undefined>\n return {\n organizationColumn: readScopeFieldName(properties.organizationId),\n tenantColumn: readScopeFieldName(properties.tenantId),\n }\n}\n\nasync function probeScopeColumns(\n db: Kysely<ScopeDatabase>,\n table: string,\n): Promise<{ organizationColumn: string | null; tenantColumn: string | null } | null> {\n let cache = probedColumnsCache.get(db)\n if (!cache) {\n cache = new Map()\n probedColumnsCache.set(db, cache)\n }\n const cached = cache.get(table)\n if (cached) return cached\n try {\n const rows = await db\n .selectFrom('information_schema.columns')\n .select(['column_name'])\n .where(sql<boolean>`table_schema = current_schema()`)\n .where('table_name', '=', table)\n .where('column_name', 'in', [ORGANIZATION_COLUMN, TENANT_COLUMN])\n .execute()\n const columns = new Set(rows.map((row) => typeof row.column_name === 'string' ? row.column_name.toLowerCase() : ''))\n const resolved = {\n organizationColumn: columns.has(ORGANIZATION_COLUMN) ? ORGANIZATION_COLUMN : null,\n tenantColumn: columns.has(TENANT_COLUMN) ? TENANT_COLUMN : null,\n }\n cache.set(table, resolved)\n return resolved\n } catch (error) {\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'shared',\n code: 'shared.scope_column_probe_failed',\n attributes: { table },\n })\n } catch (telemetryError) {\n logger.warn('Failed to report a scope column probe error', { err: telemetryError })\n }\n return null\n }\n}\n\n/**\n * Resolve which tenant/organization scope columns the table behind `entityType` actually has.\n * Uses ORM metadata when the table is registered; otherwise probes `information_schema.columns`.\n * Returns `null` when the columns cannot be determined, so callers skip the row lookup instead\n * of issuing a select that fails on global tables (e.g. `feature_toggles`).\n */\nexport async function resolveEntityScopeColumns(\n em: ScopeLookupEntityManager,\n entityType: string,\n): Promise<EntityScopeColumns | null> {\n const table = resolveEntityTableName(em as never, entityType)\n const columns = resolveScopeColumnsFromMetadata(em, table)\n ?? await probeScopeColumns(em.getKysely<ScopeDatabase>(), table)\n if (!columns) return null\n return { table, ...columns }\n}\n\n/**\n * Read the tenant/organization scope of one record by id, selecting only the scope columns its\n * table has. Returns `null` when the table has no scope columns, the columns cannot be\n * determined, or the row does not exist.\n */\nexport async function loadEntityRecordScope(\n em: ScopeLookupEntityManager,\n entityType: string,\n recordId: string,\n): Promise<EntityRecordScope | null> {\n const columns = await resolveEntityScopeColumns(em, entityType)\n if (!columns) return null\n const selected = [columns.organizationColumn, columns.tenantColumn]\n .filter((column): column is string => column !== null)\n if (selected.length === 0) return null\n const row = await em.getKysely<ScopeDatabase>()\n .selectFrom(columns.table)\n .select(selected.map((column) => sql<unknown>`${sql.ref(column)}`.as(column)))\n .where('id', '=', recordId)\n .executeTakeFirst()\n if (!row) return null\n const organizationId = columns.organizationColumn ? row[columns.organizationColumn] : null\n const tenantId = columns.tenantColumn ? row[columns.tenantColumn] : null\n return {\n organizationId: typeof organizationId === 'string' ? organizationId : null,\n tenantId: typeof tenantId === 'string' ? tenantId :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,QAAQ,EACzB,iBAAiB;AACpB,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,iBAAiB,QAAQ,qBAAqB,IAAI,QAAQ,kBAAkB,IAAI;AACtF,QAAM,WAAW,QAAQ,eAAe,IAAI,QAAQ,YAAY,IAAI;AACpE,SAAO;AAAA,IACL,gBAAgB,OAAO,mBAAmB,WAAW,iBAAiB;AAAA,IACtE,UAAU,OAAO,aAAa,WAAW,WAAW;AAAA,EACtD;AACF;AAEO,SAAS,uCAA6C;AAC3D,uBAAqB,oBAAI,QAAQ;AACnC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/lib/version.js
CHANGED
package/dist/lib/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/version.ts"],
|
|
4
|
-
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.
|
|
4
|
+
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8213.1.9d96dc8885';\nexport const appVersion = APP_VERSION;\n"],
|
|
5
5
|
"mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/shared",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8213.1.9d96dc8885",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
"@mikro-orm/core": "^7.1.14",
|
|
131
131
|
"@mikro-orm/decorators": "^7.1.14",
|
|
132
132
|
"@mikro-orm/postgresql": "^7.1.14",
|
|
133
|
-
"@open-mercato/cache": "0.10.1-develop.
|
|
133
|
+
"@open-mercato/cache": "0.10.1-develop.8213.1.9d96dc8885",
|
|
134
134
|
"@types/html-to-text": "^9.0.4",
|
|
135
135
|
"@types/sanitize-html": "^2.16.1",
|
|
136
136
|
"dotenv": "^17.4.2",
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
jest.mock('../../telemetry/runtime', () => ({ getTelemetryRuntime: jest.fn() }))
|
|
2
|
+
|
|
1
3
|
jest.mock('../../query/engine', () => ({
|
|
2
4
|
resolveEntityTableName: jest.fn((_em: unknown, entityType: string) => entityType.split(':')[1] ?? entityType),
|
|
3
5
|
}))
|
|
@@ -8,7 +10,9 @@ import {
|
|
|
8
10
|
resolveEntityScopeColumns,
|
|
9
11
|
} from '../recordScope'
|
|
10
12
|
|
|
11
|
-
|
|
13
|
+
import { getTelemetryRuntime } from '../../telemetry/runtime'
|
|
14
|
+
|
|
15
|
+
type Row = Record<string, unknown>
|
|
12
16
|
|
|
13
17
|
function buildEm(options: {
|
|
14
18
|
metadata?: Array<{ tableName: string; properties: Record<string, { fieldNames: string[] }> }>
|
|
@@ -21,7 +25,12 @@ function buildEm(options: {
|
|
|
21
25
|
selectFrom: jest.fn((table: string) => {
|
|
22
26
|
const builder = {
|
|
23
27
|
select: jest.fn((columns: unknown) => {
|
|
24
|
-
selects.push({
|
|
28
|
+
selects.push({
|
|
29
|
+
table,
|
|
30
|
+
columns: Array.isArray(columns) ? columns.map((column: unknown) => (
|
|
31
|
+
typeof column === 'string' ? column : (column as { toOperationNode: () => { alias: { name: string } } }).toOperationNode().alias.name
|
|
32
|
+
)) : columns,
|
|
33
|
+
})
|
|
25
34
|
return builder
|
|
26
35
|
}),
|
|
27
36
|
where: jest.fn(() => builder),
|
|
@@ -48,7 +57,10 @@ const scopedProperties = {
|
|
|
48
57
|
}
|
|
49
58
|
|
|
50
59
|
describe('recordScope', () => {
|
|
51
|
-
beforeEach(() =>
|
|
60
|
+
beforeEach(() => {
|
|
61
|
+
jest.clearAllMocks()
|
|
62
|
+
resetEntityScopeColumnsCacheForTests()
|
|
63
|
+
})
|
|
52
64
|
|
|
53
65
|
it('does not query a global table that has no scope columns', async () => {
|
|
54
66
|
const { em, db } = buildEm({
|
|
@@ -81,6 +93,22 @@ describe('recordScope', () => {
|
|
|
81
93
|
expect(selects).toEqual([{ table: 'tenant_things', columns: ['tenant_id'] }])
|
|
82
94
|
})
|
|
83
95
|
|
|
96
|
+
it('reads custom metadata scope column names through quoted SQL identifiers', async () => {
|
|
97
|
+
const { em, selects } = buildEm({
|
|
98
|
+
metadata: [{
|
|
99
|
+
tableName: 'custom_records',
|
|
100
|
+
properties: {
|
|
101
|
+
tenantId: { fieldNames: ['owning_tenant_id'] },
|
|
102
|
+
organizationId: { fieldNames: ['owning_organization_id'] },
|
|
103
|
+
},
|
|
104
|
+
}],
|
|
105
|
+
row: { owning_tenant_id: 'tenant-1', owning_organization_id: 'org-1' },
|
|
106
|
+
})
|
|
107
|
+
await expect(loadEntityRecordScope(em, 'mod:custom_records', 'r1'))
|
|
108
|
+
.resolves.toEqual({ tenantId: 'tenant-1', organizationId: 'org-1' })
|
|
109
|
+
expect(selects).toEqual([{ table: 'custom_records', columns: ['owning_organization_id', 'owning_tenant_id'] }])
|
|
110
|
+
})
|
|
111
|
+
|
|
84
112
|
it('returns null when the row is missing', async () => {
|
|
85
113
|
const { em } = buildEm({ metadata: [{ tableName: 'customer_people', properties: scopedProperties }] })
|
|
86
114
|
await expect(loadEntityRecordScope(em, 'customers:customer_people', 'missing')).resolves.toBeNull()
|
|
@@ -95,12 +123,35 @@ describe('recordScope', () => {
|
|
|
95
123
|
})
|
|
96
124
|
|
|
97
125
|
it('skips the row lookup when the column probe fails', async () => {
|
|
98
|
-
const
|
|
126
|
+
const error = new Error('boom')
|
|
127
|
+
const reportError = jest.fn()
|
|
128
|
+
jest.mocked(getTelemetryRuntime).mockReturnValue({ reportError } as never)
|
|
129
|
+
const { em, selects } = buildEm({ probeError: error })
|
|
99
130
|
|
|
100
131
|
await expect(loadEntityRecordScope(em, 'mod:unregistered', 'r1')).resolves.toBeNull()
|
|
101
132
|
expect(selects).toEqual([{ table: 'information_schema.columns', columns: ['column_name'] }])
|
|
133
|
+
expect(reportError).toHaveBeenCalledWith(error, {
|
|
134
|
+
module: 'shared', code: 'shared.scope_column_probe_failed', attributes: { table: 'unregistered' },
|
|
135
|
+
})
|
|
102
136
|
})
|
|
103
137
|
|
|
138
|
+
it('keeps the safe probe fallback when the telemetry backend throws', async () => {
|
|
139
|
+
jest.mocked(getTelemetryRuntime).mockReturnValue({
|
|
140
|
+
reportError: () => { throw new Error('[internal] telemetry unavailable') },
|
|
141
|
+
} as never)
|
|
142
|
+
const { em, db } = buildEm({ probeError: new Error('[internal] catalog unavailable') })
|
|
143
|
+
await expect(loadEntityRecordScope(em, 'mod:unregistered', 'r1')).resolves.toBeNull()
|
|
144
|
+
expect(db.selectFrom).toHaveBeenCalledTimes(1)
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
it('rejects non-string scope values from the database boundary', async () => {
|
|
148
|
+
const { em } = buildEm({
|
|
149
|
+
metadata: [{ tableName: 'customer_people', properties: scopedProperties }],
|
|
150
|
+
row: { tenant_id: 123, organization_id: {} },
|
|
151
|
+
})
|
|
152
|
+
await expect(loadEntityRecordScope(em, 'customers:customer_people', 'p1'))
|
|
153
|
+
.resolves.toEqual({ tenantId: null, organizationId: null })
|
|
154
|
+
})
|
|
104
155
|
it('keeps probed columns isolated between database clients', async () => {
|
|
105
156
|
const first = buildEm({ probeColumns: ['tenant_id'] })
|
|
106
157
|
const second = buildEm({ probeColumns: ['organization_id'] })
|
|
@@ -2,6 +2,10 @@ import type { Kysely } from 'kysely'
|
|
|
2
2
|
import { sql } from 'kysely'
|
|
3
3
|
import { resolveEntityTableName } from '../query/engine'
|
|
4
4
|
import { listEntityMetadata } from './entityMetadata'
|
|
5
|
+
import { getTelemetryRuntime } from '../telemetry/runtime'
|
|
6
|
+
import { createLogger } from '../logger'
|
|
7
|
+
|
|
8
|
+
const logger = createLogger('shared.recordScope')
|
|
5
9
|
|
|
6
10
|
export type EntityScopeColumns = {
|
|
7
11
|
table: string
|
|
@@ -20,7 +24,17 @@ type ScopeLookupEntityManager = {
|
|
|
20
24
|
}
|
|
21
25
|
|
|
22
26
|
type ScopePropertyMetadata = { fieldNames?: unknown }
|
|
23
|
-
type ScopeDatabase = Record<string,
|
|
27
|
+
type ScopeDatabase = Record<string, {
|
|
28
|
+
id: unknown
|
|
29
|
+
tenant_id?: unknown
|
|
30
|
+
organization_id?: unknown
|
|
31
|
+
}> & {
|
|
32
|
+
'information_schema.columns': {
|
|
33
|
+
column_name: unknown
|
|
34
|
+
table_name: unknown
|
|
35
|
+
table_schema: unknown
|
|
36
|
+
}
|
|
37
|
+
}
|
|
24
38
|
|
|
25
39
|
const ORGANIZATION_COLUMN = 'organization_id'
|
|
26
40
|
const TENANT_COLUMN = 'tenant_id'
|
|
@@ -73,7 +87,16 @@ async function probeScopeColumns(
|
|
|
73
87
|
}
|
|
74
88
|
cache.set(table, resolved)
|
|
75
89
|
return resolved
|
|
76
|
-
} catch {
|
|
90
|
+
} catch (error) {
|
|
91
|
+
try {
|
|
92
|
+
getTelemetryRuntime()?.reportError(error, {
|
|
93
|
+
module: 'shared',
|
|
94
|
+
code: 'shared.scope_column_probe_failed',
|
|
95
|
+
attributes: { table },
|
|
96
|
+
})
|
|
97
|
+
} catch (telemetryError) {
|
|
98
|
+
logger.warn('Failed to report a scope column probe error', { err: telemetryError })
|
|
99
|
+
}
|
|
77
100
|
return null
|
|
78
101
|
}
|
|
79
102
|
}
|
|
@@ -89,7 +112,6 @@ export async function resolveEntityScopeColumns(
|
|
|
89
112
|
entityType: string,
|
|
90
113
|
): Promise<EntityScopeColumns | null> {
|
|
91
114
|
const table = resolveEntityTableName(em as never, entityType)
|
|
92
|
-
if (!table) return null
|
|
93
115
|
const columns = resolveScopeColumnsFromMetadata(em, table)
|
|
94
116
|
?? await probeScopeColumns(em.getKysely<ScopeDatabase>(), table)
|
|
95
117
|
if (!columns) return null
|
|
@@ -113,7 +135,7 @@ export async function loadEntityRecordScope(
|
|
|
113
135
|
if (selected.length === 0) return null
|
|
114
136
|
const row = await em.getKysely<ScopeDatabase>()
|
|
115
137
|
.selectFrom(columns.table)
|
|
116
|
-
.select(selected)
|
|
138
|
+
.select(selected.map((column) => sql<unknown>`${sql.ref(column)}`.as(column)))
|
|
117
139
|
.where('id', '=', recordId)
|
|
118
140
|
.executeTakeFirst()
|
|
119
141
|
if (!row) return null
|