@crombolo/data 0.47.0 → 0.48.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/data",
3
- "version": "0.47.0",
3
+ "version": "0.48.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,7 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.47.0",
31
+ "@crombolo/core": "0.48.1",
32
32
  "kysely": "0.29.6"
33
33
  }
34
34
  }
@@ -15,6 +15,7 @@ import {
15
15
  import type { Db } from './database.ts'
16
16
  import { DbDate, fromDbBool } from './dialect.ts'
17
17
  import { type Expression, sql } from './query.ts'
18
+ import { fullTextHits } from './search-providers.ts'
18
19
  import { escapeLike, searchTerms } from './search-text.ts'
19
20
 
20
21
  export const QUERY_STATES = ['published', 'draft', 'changed', 'trashed'] as const
@@ -441,8 +442,10 @@ async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise
441
442
 
442
443
  // ---- full text, through the existing index
443
444
  if (query.text) {
444
- const hits = db.dialect.fullTextMatches(db.dialect.fullTextQuery(searchTerms(query.text)))
445
- q = q.where((eb) => eb('n.id', 'in', eb.selectFrom(hits.as('h')).select('h.node_id')))
445
+ const hits = await fullTextHits(db, query.text, ['document'])
446
+ q = hits
447
+ ? q.where((eb) => eb('n.id', 'in', eb.selectFrom(hits.as('h')).select('h.node_id')))
448
+ : q.where(sql<boolean>`${sql.lit(false)}`)
446
449
  }
447
450
 
448
451
  // ---- properties
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ export * from './repositories/content-types.ts'
25
25
  export * from './repositories/data-types.ts'
26
26
  export * from './repositories/delivery-member-tokens.ts'
27
27
  export * from './repositories/dictionary.ts'
28
+ export * from './repositories/document-listing.ts'
28
29
  export * from './repositories/documents.ts'
29
30
  export * from './repositories/domains.ts'
30
31
  export * from './repositories/dynamic-roots.ts'
@@ -102,6 +103,7 @@ export * from './schema/remote.ts'
102
103
  export * from './schema/remote-trust.ts'
103
104
  export * from './schema/rich-text-ui.ts'
104
105
  export * from './schema/search-index.ts'
106
+ export * from './schema/search-removals.ts'
105
107
  export * from './schema/seed.ts'
106
108
  export * from './schema/since-version.ts'
107
109
  export * from './schema/site-search.ts'
@@ -118,6 +120,7 @@ export * from './schema/webhooks.ts'
118
120
  export * from './schema-ops.ts'
119
121
  export * from './schema-state.ts'
120
122
  export * from './search.ts'
123
+ export * from './search-providers.ts'
121
124
  export * from './search-text.ts'
122
125
  export * from './setup.ts'
123
126
  export * from './site-search.ts'
@@ -0,0 +1,209 @@
1
+ /**
2
+ * A page's children as its list view shows them (story 269): searched by name,
3
+ * sorted by a built-in column or a property's value (story 276) and paged in
4
+ * the database, with who created and last edited each one.
5
+ */
6
+ import { normaliseUuid, ObjectTypes } from '@crombolo/core'
7
+ import type { ExpressionBuilder, SelectQueryBuilder, SqlBool } from 'kysely'
8
+ import type { Db } from '../database.ts'
9
+ import { type Expression, sql } from '../query.ts'
10
+ import type { CoreTables } from '../tables.gen.ts'
11
+
12
+ export type DocumentSortField =
13
+ | 'createDate'
14
+ | 'updateDate'
15
+ | 'name'
16
+ | 'sortOrder'
17
+ | 'creator'
18
+ | 'updater'
19
+
20
+ export interface DocumentListingQuery {
21
+ parentId: number
22
+ /** Every one must appear in the name shown, ignoring case. */
23
+ names?: readonly string[]
24
+ /** A built-in column, or a property's current draft value by its alias (story 276). */
25
+ sort?: { field: DocumentSortField; ascending: boolean } | { property: string; ascending: boolean }
26
+ /** The culture whose names are searched and sorted; the draft name otherwise. */
27
+ culture?: string | null
28
+ excludeKeys?: readonly string[]
29
+ skip: number
30
+ take: number
31
+ }
32
+
33
+ type Listed = {
34
+ n: CoreTables['node']
35
+ head: CoreTables['content_version']
36
+ dcv: CoreTables['document_culture_variation']
37
+ lang: CoreTables['language']
38
+ made: CoreTables['user_account']
39
+ edited: CoreTables['user_account']
40
+ }
41
+ type Aliases = keyof Listed
42
+ type Eb = ExpressionBuilder<CoreTables & Listed, Aliases>
43
+
44
+ const nameOf = (eb: Eb) => eb.fn.coalesce('dcv.name', 'head.text', 'n.text')
45
+
46
+ const SORT_COLUMNS: Record<DocumentSortField, (eb: Eb) => Expression<unknown>> = {
47
+ createDate: (eb) => eb.ref('n.create_date'),
48
+ updateDate: (eb) => eb.fn.coalesce('head.version_date', 'n.create_date'),
49
+ name: (eb) => eb.fn('lower', [nameOf(eb)]),
50
+ sortOrder: (eb) => eb.ref('n.sort_order'),
51
+ creator: (eb) => eb.fn('lower', [eb.ref('made.user_name')]),
52
+ updater: (eb) => eb.fn('lower', [eb.ref('edited.user_name')]),
53
+ }
54
+
55
+ /** A property value's columns, in the order a sort reads them: one is set, by its storage. */
56
+ const VALUE_COLUMNS = ['int_value', 'decimal_value', 'date_value', 'sortable_value'] as const
57
+
58
+ /**
59
+ * The current draft value of the property `alias` for the row's page, in the
60
+ * culture shown when it varies, from one column: a correlated subquery, so a
61
+ * page is listed once whatever its values.
62
+ */
63
+ function propertyValue(eb: Eb, db: Db, alias: string, column: (typeof VALUE_COLUMNS)[number]) {
64
+ const inner = eb as unknown as ExpressionBuilder<
65
+ CoreTables & Listed & { pv: CoreTables['property_value']; pt: CoreTables['property_type'] },
66
+ Aliases | 'pv' | 'pt'
67
+ >
68
+ return inner
69
+ .selectFrom('property_value as pv')
70
+ .innerJoin('property_type as pt', 'pt.id', 'pv.property_type_id')
71
+ .select(
72
+ column === 'sortable_value'
73
+ ? (e) => e.fn('lower', [e.ref('pv.sortable_value')]).as('v')
74
+ : (e) => e.ref(`pv.${column}`).as('v'),
75
+ )
76
+ .whereRef('pv.node_id', '=', 'n.id')
77
+ .where('pt.alias', '=', alias)
78
+ .where('pt.retired_at', 'is', null)
79
+ .where('pv.is_current', '=', db.dialect.boolValue(true) as boolean)
80
+ .where('pv.segment', 'is', null)
81
+ .where((e) =>
82
+ e.or([e('pv.language_id', 'is', null), e('pv.language_id', '=', e.ref('lang.id'))]),
83
+ )
84
+ .orderBy('pv.id', 'desc')
85
+ .limit(1)
86
+ }
87
+
88
+ const likeEscape = (value: string) => value.replace(/[\\%_]/g, (c) => `\\${c}`)
89
+
90
+ export class DocumentListingRepository {
91
+ #db: Db
92
+
93
+ constructor(db: Db) {
94
+ this.#db = db
95
+ }
96
+
97
+ /** A page of a parent's children: their keys in order, and how many match in all. */
98
+ async children(query: DocumentListingQuery): Promise<{ total: number; keys: string[] }> {
99
+ const names = query.names ?? []
100
+ const excluded = (query.excludeKeys ?? []).map(normaliseUuid)
101
+ const db = this.#db
102
+ const listing = () =>
103
+ (
104
+ db.q.selectFrom('node as n') as unknown as SelectQueryBuilder<
105
+ CoreTables & Listed,
106
+ Aliases,
107
+ object
108
+ >
109
+ )
110
+ .leftJoin('content_version as head', (join) =>
111
+ join
112
+ .onRef('head.node_id', '=', 'n.id')
113
+ .on('head.current', '=', db.dialect.boolValue(true)),
114
+ )
115
+ .leftJoin('language as lang', (join) =>
116
+ join.on((eb) =>
117
+ eb(eb.fn('lower', [eb.ref('lang.iso_code')]), '=', (query.culture ?? '').toLowerCase()),
118
+ ),
119
+ )
120
+ .leftJoin('document_culture_variation as dcv', (join) =>
121
+ join.onRef('dcv.node_id', '=', 'n.id').onRef('dcv.language_id', '=', 'lang.id'),
122
+ )
123
+ .leftJoin('user_account as made', 'made.id', 'n.node_user')
124
+ .leftJoin('user_account as edited', 'edited.id', 'head.user_id')
125
+ .where('n.parent_id', '=', query.parentId)
126
+ .where('n.node_object_type', '=', ObjectTypes.Document)
127
+ .where('n.trashed', '=', db.dialect.boolValue(false))
128
+ .$if(excluded.length > 0, (q) => q.where('n.unique_id', 'not in', excluded))
129
+ .$call((q) =>
130
+ names.reduce(
131
+ (acc, part) =>
132
+ acc.where(
133
+ (eb) =>
134
+ sql<SqlBool>`${eb.fn('lower', [nameOf(eb)])} like ${`%${likeEscape(part.toLowerCase())}%`} escape '\\'`,
135
+ ),
136
+ q,
137
+ ),
138
+ )
139
+ const counted = await listing().select(sql<number>`count(*)`.as('n')).executeTakeFirst()
140
+ const sort = query.sort
141
+ const rows =
142
+ query.take <= 0
143
+ ? []
144
+ : await listing()
145
+ .select('n.unique_id')
146
+ .$call((q) => {
147
+ if (!sort) return q
148
+ const direction = sort.ascending ? 'asc' : 'desc'
149
+ if ('field' in sort) return q.orderBy((eb) => SORT_COLUMNS[sort.field](eb), direction)
150
+ // Pages with no value come last either way, then by the column the value is kept in.
151
+ const sorted = q.orderBy(
152
+ (eb) =>
153
+ eb
154
+ .case()
155
+ .when(
156
+ eb.or(
157
+ VALUE_COLUMNS.map((column) =>
158
+ eb(propertyValue(eb, db, sort.property, column), 'is not', null),
159
+ ),
160
+ ),
161
+ )
162
+ .then(0)
163
+ .else(1)
164
+ .end(),
165
+ 'asc',
166
+ )
167
+ return VALUE_COLUMNS.reduce(
168
+ (acc, column) =>
169
+ acc.orderBy((eb) => propertyValue(eb, db, sort.property, column), direction),
170
+ sorted,
171
+ )
172
+ })
173
+ .orderBy('n.sort_order')
174
+ .orderBy('n.id')
175
+ .limit(query.take)
176
+ .offset(Math.max(0, query.skip))
177
+ .execute()
178
+ return {
179
+ total: Number(counted?.n ?? 0),
180
+ keys: rows.map((row) => normaliseUuid(String(row.unique_id))),
181
+ }
182
+ }
183
+
184
+ /** Who created each page and who saved its current draft, by key, in one query. */
185
+ async people(
186
+ keys: readonly string[],
187
+ ): Promise<Map<string, { creator: string | null; updater: string | null }>> {
188
+ const out = new Map<string, { creator: string | null; updater: string | null }>()
189
+ if (keys.length === 0) return out
190
+ const rows = await this.#db.q
191
+ .selectFrom('node as n')
192
+ .leftJoin('content_version as head', (join) =>
193
+ join
194
+ .onRef('head.node_id', '=', 'n.id')
195
+ .on('head.current', '=', this.#db.dialect.boolValue(true)),
196
+ )
197
+ .leftJoin('user_account as made', 'made.id', 'n.node_user')
198
+ .leftJoin('user_account as edited', 'edited.id', 'head.user_id')
199
+ .select(['n.unique_id', 'made.user_name as creator', 'edited.user_name as updater'])
200
+ .where('n.unique_id', 'in', keys.map(normaliseUuid))
201
+ .execute()
202
+ for (const row of rows)
203
+ out.set(normaliseUuid(String(row.unique_id)), {
204
+ creator: row.creator ? String(row.creator) : null,
205
+ updater: row.updater ? String(row.updater) : null,
206
+ })
207
+ return out
208
+ }
209
+ }
@@ -42,6 +42,7 @@ import {
42
42
  visibleStateIdFor,
43
43
  } from '../schema-state.ts'
44
44
  import { queueForSearch } from '../search.ts'
45
+ import { recordSearchRemovals, searchesOutsideDatabase } from '../search-providers.ts'
45
46
  import type { CoreTables } from '../tables.gen.ts'
46
47
  import { recordFiles } from './media-access.ts'
47
48
  import { NodeRepository, type NodeRow } from './nodes.ts'
@@ -1521,6 +1522,21 @@ export class DocumentRepository {
1521
1522
  .set({ sort_order: await repo.#nextSortOrder(parentId, node.id) })
1522
1523
  .where('id', '=', node.id)
1523
1524
  .execute()
1525
+ // A provider outside the database filters on the paths it was given (story 273).
1526
+ const placed = searchesOutsideDatabase(tx) ? await repo.nodes.byId(node.id) : undefined
1527
+ if (placed) {
1528
+ const moved = await tx.q
1529
+ .selectFrom('node')
1530
+ .select('id')
1531
+ .where((eb) =>
1532
+ eb.or([eb('id', '=', placed.id), eb('path', 'like', `${placed.path},%`)]),
1533
+ )
1534
+ .execute()
1535
+ await queueForSearch(
1536
+ tx,
1537
+ moved.map((row) => Number(row.id)),
1538
+ )
1539
+ }
1524
1540
  await repo.#instructContent(node.key)
1525
1541
  return 'moved'
1526
1542
  }),
@@ -2747,7 +2763,33 @@ export class DocumentRepository {
2747
2763
  }
2748
2764
 
2749
2765
  /**
2750
- * The content tree's view of documents: four queries a page, whatever its
2766
+ * Whether each page has public access rules of its own or from a page above
2767
+ * it, as Umbraco's `isProtected` means, in one read for them all.
2768
+ */
2769
+ async protectedKeys(rows: readonly NodeRow[]): Promise<Set<string>> {
2770
+ const pathIds = (row: NodeRow) =>
2771
+ row.path
2772
+ .split(',')
2773
+ .map(Number)
2774
+ .filter((id) => id > 0)
2775
+ const guarded = await this.#protectedIds([...new Set(rows.flatMap(pathIds))])
2776
+ return new Set(
2777
+ rows.filter((row) => pathIds(row).some((id) => guarded.has(id))).map((row) => row.key),
2778
+ )
2779
+ }
2780
+
2781
+ async #protectedIds(ids: readonly number[]): Promise<Set<number>> {
2782
+ if (ids.length === 0 || this.objectType !== ObjectTypes.Document) return new Set()
2783
+ const rows = await this.#db.q
2784
+ .selectFrom('public_access')
2785
+ .select('node_id')
2786
+ .where('node_id', 'in', ids)
2787
+ .execute()
2788
+ return new Set(rows.map((row) => Number(row.node_id)))
2789
+ }
2790
+
2791
+ /**
2792
+ * The content tree's view of documents: five queries a page, whatever its
2751
2793
  * size. Only what a tree item shows is read — not the values, nor the
2752
2794
  * schedules the editor needs.
2753
2795
  */
@@ -2803,6 +2845,40 @@ export class DocumentRepository {
2803
2845
  const above = new Map(
2804
2846
  (await this.#nodes.byIds([...new Set(rows.flatMap(pathIds))])).map((n) => [n.id, n]),
2805
2847
  )
2848
+ // Public access on the pages or above them, and their publishes to come, in one read.
2849
+ const marks = await this.#db.q
2850
+ .selectFrom('public_access')
2851
+ .select((eb) => [
2852
+ 'node_id',
2853
+ eb.val('protected').as('mark'),
2854
+ sql<string | null>`null`.as('iso_code'),
2855
+ ])
2856
+ .where(
2857
+ 'node_id',
2858
+ 'in',
2859
+ this.objectType === ObjectTypes.Document
2860
+ ? [...new Set([...ids, ...rows.flatMap(pathIds)])]
2861
+ : [-1],
2862
+ )
2863
+ .unionAll((eb) =>
2864
+ eb
2865
+ .selectFrom('content_schedule as s')
2866
+ .leftJoin('language as l', 'l.id', 's.language_id')
2867
+ .select((e) => ['s.node_id', e.val('release').as('mark'), 'l.iso_code'])
2868
+ .where('s.node_id', 'in', ids)
2869
+ .where('s.action', '=', 'Release'),
2870
+ )
2871
+ .execute()
2872
+ const guarded = new Set(
2873
+ marks.filter((m) => m.mark === 'protected').map((m) => Number(m.node_id)),
2874
+ )
2875
+ const releases = marks.filter((m) => m.mark === 'release')
2876
+ const scheduled = (id: number, culture: string | null) =>
2877
+ releases.some(
2878
+ (r) =>
2879
+ Number(r.node_id) === id &&
2880
+ ((r.iso_code as string | null) ?? null)?.toLowerCase() === culture?.toLowerCase(),
2881
+ )
2806
2882
 
2807
2883
  const items: DocumentTreeItem[] = []
2808
2884
  for (const row of rows) {
@@ -2826,6 +2902,7 @@ export class DocumentRepository {
2826
2902
  isTrashed: row.trashed,
2827
2903
  createDate: row.createDate ?? new Date(),
2828
2904
  ancestorKeys: ancestors.filter((a) => a.objectType === this.objectType).map((a) => a.key),
2905
+ isProtected: guarded.has(row.id) || pathIds(row).some((id) => guarded.has(id)),
2829
2906
  variants:
2830
2907
  own.length === 0
2831
2908
  ? [
@@ -2833,11 +2910,13 @@ export class DocumentRepository {
2833
2910
  culture: null,
2834
2911
  name: String(fact.draft_name ?? row.text ?? ''),
2835
2912
  state: stateFor(fromDbBool(fact.published), fromDbBool(fact.edited), row.trashed),
2913
+ scheduledForPublish: scheduled(row.id, null),
2836
2914
  },
2837
2915
  ]
2838
2916
  : own.map((c) => ({
2839
2917
  culture: String(c.iso_code),
2840
2918
  name: String(c.name ?? ''),
2919
+ scheduledForPublish: scheduled(row.id, String(c.iso_code)),
2841
2920
  state: stateFor(
2842
2921
  fromDbBool(c.published),
2843
2922
  fromDbBool(c.edited),
@@ -3429,6 +3508,11 @@ async function deleteNodeRows(
3429
3508
  )
3430
3509
  const versions = () =>
3431
3510
  tx.q.selectFrom('content_version').select('id').where('node_id', 'in', nodes())
3511
+ // Search providers outside the database lose nothing by cascade, so they are told (story 273).
3512
+ await recordSearchRemovals(
3513
+ tx,
3514
+ (await nodes().execute()).map((row) => Number(row.id)),
3515
+ )
3432
3516
  await tx.q.deleteFrom('property_value').where('node_id', 'in', nodes()).execute()
3433
3517
  await tx.q.deleteFrom('content_schedule').where('node_id', 'in', nodes()).execute()
3434
3518
  await tx.q.deleteFrom('user_notification').where('node_id', 'in', nodes()).execute()
@@ -17,7 +17,7 @@ import type { Db } from '../database.ts'
17
17
  import { DbDate, fromDbBool } from '../dialect.ts'
18
18
  import { type Expression, sql } from '../query.ts'
19
19
  import { queueForSearch } from '../search.ts'
20
- import { searchTerms } from '../search-text.ts'
20
+ import { fullTextHits } from '../search-providers.ts'
21
21
  import {
22
22
  DocumentRepository,
23
23
  type DocumentRepositoryOptions,
@@ -385,7 +385,7 @@ export class MemberRepository {
385
385
  async filter(criteria: MemberFilter): Promise<{ total: number; items: MemberCredentials[] }> {
386
386
  const db = this.#db
387
387
  const text = criteria.filter?.trim()
388
- const terms = text ? searchTerms(text) : []
388
+ const hits = text ? await fullTextHits(db, text, ['member']) : undefined
389
389
  const base = joined(db).where((eb) => {
390
390
  const all: Expression<SqlBool>[] = []
391
391
  if (criteria.memberTypeKey)
@@ -421,14 +421,12 @@ export class MemberRepository {
421
421
  eb(eb.fn('lower', ['n.text']), 'like', like),
422
422
  ]
423
423
  // The index adds what a member's properties say to the name, username and e-mail.
424
- if (terms.length > 0)
424
+ if (hits)
425
425
  any.push(
426
426
  eb(
427
427
  'm.node_id',
428
428
  'in',
429
- eb
430
- .selectFrom(db.dialect.fullTextMatches(db.dialect.fullTextQuery(terms)).as('h'))
431
- .select(sql<number>`node_id`.as('node_id')),
429
+ eb.selectFrom(hits.as('h')).select(sql<number>`node_id`.as('node_id')),
432
430
  ),
433
431
  )
434
432
  all.push(eb.or(any))
@@ -8,7 +8,7 @@ import { normaliseUuid, ObjectTypes, type Page, SystemNodes } from '@crombolo/co
8
8
  import type { Db } from '../database.ts'
9
9
  import { DbDate, fromDbBool } from '../dialect.ts'
10
10
  import { sql } from '../query.ts'
11
- import { searchTerms } from '../search-text.ts'
11
+ import { fullTextHits, kindOf } from '../search-providers.ts'
12
12
 
13
13
  export interface NodeRow {
14
14
  id: number
@@ -361,8 +361,9 @@ export class NodeRepository {
361
361
  },
362
362
  ): Promise<Page<NodeRow>> {
363
363
  const like = `%${query.toLowerCase().replaceAll('%', '').replaceAll('_', '')}%`
364
- const terms = options.fullText ? searchTerms(query) : []
365
- const indexed = terms.length > 0
364
+ const kind = kindOf(objectType)
365
+ const hits = options.fullText && kind ? await fullTextHits(this.#db, query, [kind]) : undefined
366
+ const indexed = hits !== undefined
366
367
  const dialect = this.#db.dialect
367
368
  const hitNode = sql.ref<number | null>('h.node_id')
368
369
  const hitScore = sql.ref<number | null>('h.score')
@@ -373,7 +374,7 @@ export class NodeRepository {
373
374
  indexed,
374
375
  (q) =>
375
376
  q.leftJoin(
376
- dialect.fullTextMatches(dialect.fullTextQuery(terms)).as('h'),
377
+ (hits as NonNullable<typeof hits>).as('h'),
377
378
  'h.node_id',
378
379
  'node.id',
379
380
  ) as unknown as typeof q,
@@ -62,6 +62,7 @@ import { remoteMigration } from './remote.ts'
62
62
  import { remoteTrustMigration } from './remote-trust.ts'
63
63
  import { richTextUiMigration } from './rich-text-ui.ts'
64
64
  import { searchIndexMigration } from './search-index.ts'
65
+ import { searchRemovalsMigration } from './search-removals.ts'
65
66
  import { serverRoleMigration } from './server-role.ts'
66
67
  import { sinceVersionMigration } from './since-version.ts'
67
68
  import { siteSearchMigration } from './site-search.ts'
@@ -139,4 +140,5 @@ export const cromboloPlan = new MigrationPlan([
139
140
  bundlesInSettingsMigration,
140
141
  remoteTrustMigration,
141
142
  mediaTreeOrderMigration,
143
+ searchRemovalsMigration,
142
144
  ])
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Migration 063: what a search provider must forget (story 273). Deleting a
3
+ * page, media item or member for good takes its database index rows with it,
4
+ * but a provider that is not the database has to be told. A row is written in
5
+ * the delete's own transaction and taken by the indexer once every provider
6
+ * has removed the item. docs/search.md, "Providers".
7
+ */
8
+ import type { Db } from '../database.ts'
9
+ import type { Migration } from '../migrations.ts'
10
+ import { sql } from '../query.ts'
11
+ import { STATE_MEDIA_TREE_ORDER } from './media-tree-order.ts'
12
+
13
+ export const STATE_SEARCH_REMOVALS = '{c3e7a512-0063-4f0b-9d61-a8b2c4e60063}'
14
+
15
+ export const searchRemovalsMigration: Migration = {
16
+ from: STATE_MEDIA_TREE_ORDER,
17
+ to: STATE_SEARCH_REMOVALS,
18
+ name: 'AddSearchRemovals',
19
+ kind: 'expand',
20
+ release: '0.48.0',
21
+ async up(db: Db) {
22
+ const t = db.dialect.types
23
+ await db.q.schema
24
+ .createTable('search_removal')
25
+ .addColumn('id', sql.raw(t.identity))
26
+ .addColumn('node_id', sql.raw(t.integer), (c) => c.notNull())
27
+ .addColumn('node_key', sql.raw(t.text), (c) => c.notNull())
28
+ .addColumn('kind', sql.raw(t.text), (c) => c.notNull())
29
+ .addColumn('removed_at', sql.raw(t.timestamp), (c) => c.notNull())
30
+ .execute()
31
+ },
32
+ }
@@ -0,0 +1,385 @@
1
+ /**
2
+ * The search providers a database answers with (story 273): the database
3
+ * ones by default, or a site's own, registered per connection so every handle
4
+ * on it, transactions included, finds the same. The queries that join the
5
+ * full-text match into their own SQL read it through `fullTextHits`, and what
6
+ * a delete takes away waits in `search_removal` for providers outside the
7
+ * database. docs/search.md, "Providers".
8
+ */
9
+ import {
10
+ BACKOFFICE_INDEX_KINDS,
11
+ type BackofficeIndexName,
12
+ type BackofficeSearchEntry,
13
+ type BackofficeSearchHit,
14
+ type BackofficeSearchProvider,
15
+ ObjectTypes,
16
+ type SearchItem,
17
+ type SearchKind,
18
+ type SearchMatch,
19
+ type SiteSearchEntry,
20
+ type SiteSearchHit,
21
+ type SiteSearchProvider,
22
+ type SiteSearchQuery,
23
+ searchTerms,
24
+ } from '@crombolo/core'
25
+ import type { RawBuilder } from 'kysely'
26
+ import type { Db } from './database.ts'
27
+ import { DbDate, type FullTextHit, fromDbBool } from './dialect.ts'
28
+ import { sql } from './query.ts'
29
+
30
+ export const KIND_OBJECT_TYPES: Readonly<Record<SearchKind, string>> = {
31
+ document: ObjectTypes.Document,
32
+ media: ObjectTypes.Media,
33
+ member: ObjectTypes.Member,
34
+ }
35
+
36
+ export function kindOf(objectType: string): SearchKind | undefined {
37
+ return (Object.keys(KIND_OBJECT_TYPES) as SearchKind[]).find(
38
+ (kind) => KIND_OBJECT_TYPES[kind] === objectType,
39
+ )
40
+ }
41
+
42
+ /** A provider kept in this database: the indexer writes it inside the claim's transaction. */
43
+ export interface InDatabase<E> {
44
+ readonly inDatabase: true
45
+ writeIn(tx: Db, item: Pick<SearchItem, 'id'>, entries: readonly E[]): Promise<void>
46
+ }
47
+
48
+ export type DatabaseBackofficeSearch = BackofficeSearchProvider &
49
+ InDatabase<BackofficeSearchEntry> & {
50
+ /** The full-text match as a subquery of `node_id` and `score`, to join in SQL. */
51
+ sqlMatches(query: string): RawBuilder<FullTextHit> | undefined
52
+ }
53
+
54
+ export type DatabaseSiteSearch = SiteSearchProvider & InDatabase<SiteSearchEntry>
55
+
56
+ export function isInDatabase<E>(provider: object): provider is InDatabase<E> {
57
+ return (provider as Partial<InDatabase<E>>).inDatabase === true
58
+ }
59
+
60
+ async function writeBackofficeRows(
61
+ tx: Db,
62
+ nodeId: number,
63
+ entries: readonly BackofficeSearchEntry[],
64
+ ): Promise<void> {
65
+ await tx.q.deleteFrom('search_document').where('node_id', '=', nodeId).execute()
66
+ const indexedAt = DbDate.toDb(new Date())
67
+ for (const entry of entries)
68
+ await tx.q
69
+ .insertInto('search_document')
70
+ .values({
71
+ node_id: nodeId,
72
+ culture: entry.culture,
73
+ name: entry.name,
74
+ body: entry.body,
75
+ fields: JSON.stringify(entry.fields),
76
+ field_count: Object.keys(entry.fields).length,
77
+ indexed_at: indexedAt,
78
+ })
79
+ .execute()
80
+ }
81
+
82
+ /** Backoffice search over `search_document`: FTS5 on SQLite, `tsvector` on Postgres. */
83
+ export function databaseBackofficeSearch(db: Db): DatabaseBackofficeSearch {
84
+ const sqlMatches = (query: string) => {
85
+ const terms = searchTerms(query)
86
+ return terms.length > 0
87
+ ? db.dialect.fullTextMatches(db.dialect.fullTextQuery(terms))
88
+ : undefined
89
+ }
90
+ const objectTypes = (index: BackofficeIndexName) =>
91
+ BACKOFFICE_INDEX_KINDS[index].map((kind) => KIND_OBJECT_TYPES[kind])
92
+ return {
93
+ name: 'the database',
94
+ inDatabase: true,
95
+ sqlMatches,
96
+ writeIn: (tx, item, entries) => writeBackofficeRows(tx, item.id, entries),
97
+ write: (item, entries) => writeBackofficeRows(db, item.id, entries),
98
+ async remove(item) {
99
+ await db.q.deleteFrom('search_document').where('node_id', '=', item.id).execute()
100
+ },
101
+ async matches(query, options): Promise<SearchMatch[]> {
102
+ const hits = sqlMatches(query)
103
+ if (!hits || options.kinds.length === 0) return []
104
+ const rows = await db.q
105
+ .selectFrom(hits.as('h'))
106
+ .innerJoin('node as n', 'n.id', 'h.node_id')
107
+ .select(['n.id', 'h.score'])
108
+ .where(
109
+ 'n.node_object_type',
110
+ 'in',
111
+ options.kinds.map((kind) => KIND_OBJECT_TYPES[kind]),
112
+ )
113
+ .orderBy('h.score', 'desc')
114
+ .orderBy('n.id')
115
+ .limit(options.limit)
116
+ .execute()
117
+ return rows.map((row) => ({ id: Number(row.id), score: Number(row.score) }))
118
+ },
119
+ async query(index, query, paging) {
120
+ const hits = sqlMatches(query)
121
+ if (!hits) return { total: 0, items: [] }
122
+ const matching = db.q
123
+ .selectFrom(hits.as('h'))
124
+ .innerJoin('node as n', 'n.id', 'h.node_id')
125
+ .where('n.node_object_type', 'in', objectTypes(index))
126
+ const count = await matching.select((eb) => eb.fn.countAll().as('n')).executeTakeFirst()
127
+ const rows = await matching
128
+ .select(['n.id', 'n.unique_id as key', 'h.score'])
129
+ .orderBy('h.score', 'desc')
130
+ .orderBy('n.id')
131
+ .limit(paging.take)
132
+ .offset(paging.skip)
133
+ .execute()
134
+ const items: BackofficeSearchHit[] = []
135
+ for (const row of rows) {
136
+ const stored = await db.q
137
+ .selectFrom('search_document')
138
+ .select('fields')
139
+ .where('node_id', '=', Number(row.id))
140
+ .orderBy('culture')
141
+ .execute()
142
+ const merged = new Map<string, string[]>()
143
+ for (const entry of stored)
144
+ for (const [name, values] of Object.entries(
145
+ JSON.parse(entry.fields) as Record<string, string[]>,
146
+ ))
147
+ merged.set(name, [...new Set([...(merged.get(name) ?? []), ...values])])
148
+ items.push({
149
+ key: String(row.key),
150
+ score: Number(row.score),
151
+ fields: [...merged].map(([name, values]) => ({ name, values })),
152
+ })
153
+ }
154
+ return { total: Number(count?.n ?? 0), items }
155
+ },
156
+ async stats(index) {
157
+ const row = await db.q
158
+ .selectFrom('search_document as sd')
159
+ .innerJoin('node as n', 'n.id', 'sd.node_id')
160
+ .select((eb) => [
161
+ eb.fn.count('sd.node_id').distinct().as('n'),
162
+ eb.fn.max('sd.field_count').as('fields'),
163
+ ])
164
+ .where('n.node_object_type', 'in', objectTypes(index))
165
+ .executeTakeFirst()
166
+ return { documentCount: Number(row?.n ?? 0), fieldCount: Number(row?.fields ?? 0) }
167
+ },
168
+ health: async () => ({ ok: true }),
169
+ }
170
+ }
171
+
172
+ /** Site search over `site_search_document`, weighted by `site-search` level. */
173
+ export function databaseSiteSearch(
174
+ db: Db,
175
+ rows: {
176
+ write(tx: Db, nodeId: number, entries: readonly SiteSearchEntry[]): Promise<void>
177
+ query(
178
+ db: Db,
179
+ query: string,
180
+ options: SiteSearchQuery,
181
+ ): Promise<{ total: number; items: SiteSearchHit[] }>
182
+ },
183
+ ): DatabaseSiteSearch {
184
+ return {
185
+ name: 'the database',
186
+ inDatabase: true,
187
+ writeIn: (tx, item, entries) => rows.write(tx, item.id, entries),
188
+ write: (item, entries) => rows.write(db, item.id, entries),
189
+ async remove(item) {
190
+ await db.q.deleteFrom('site_search_document').where('node_id', '=', item.id).execute()
191
+ },
192
+ query: (query, options) => rows.query(db, query, options),
193
+ async stats() {
194
+ const row = await db.q
195
+ .selectFrom('site_search_document')
196
+ .select((eb) => eb.fn.count('node_id').distinct().as('n'))
197
+ .executeTakeFirst()
198
+ return { documentCount: Number(row?.n ?? 0) }
199
+ },
200
+ health: async () => ({ ok: true }),
201
+ }
202
+ }
203
+
204
+ export interface SearchProviders {
205
+ backoffice: BackofficeSearchProvider
206
+ site: SiteSearchProvider
207
+ /** How many matches a query joining them takes from a provider outside the database. */
208
+ matchLimit: number
209
+ /** Told of a provider's failure; the item stays queued and is tried again. */
210
+ onError?: (error: unknown, context: { provider: string; key?: string }) => void
211
+ /** Told once a query took `matchLimit` matches, so its total may be capped. */
212
+ onCapped?: () => void
213
+ }
214
+
215
+ export const DEFAULT_MATCH_LIMIT = 1000
216
+
217
+ const registered = new WeakMap<object, SearchProviders>()
218
+ const defaults = new WeakMap<object, SearchProviders>()
219
+
220
+ /**
221
+ * The providers `db` searches with: what `useSearchProviders` registered, else
222
+ * the database ones. Kept per connection, so its transactions see the same.
223
+ */
224
+ export function searchProvidersOf(db: Db): SearchProviders {
225
+ const found = registered.get(db.locks)
226
+ if (found) return found
227
+ let fallback = defaults.get(db.locks)
228
+ if (!fallback) {
229
+ fallback = {
230
+ backoffice: databaseBackofficeSearch(db),
231
+ site: defaultSiteSearch(db),
232
+ matchLimit: DEFAULT_MATCH_LIMIT,
233
+ }
234
+ defaults.set(db.locks, fallback)
235
+ }
236
+ return fallback
237
+ }
238
+
239
+ /** Whether either search is kept outside this database, so it must be told what changes here. */
240
+ export function searchesOutsideDatabase(db: Db): boolean {
241
+ const { backoffice, site } = searchProvidersOf(db)
242
+ return !isInDatabase(backoffice) || !isInDatabase(site)
243
+ }
244
+
245
+ /** Registers the providers every handle on `db`'s connection searches with. */
246
+ export function useSearchProviders(db: Db, providers: Partial<SearchProviders>): SearchProviders {
247
+ const base = searchProvidersOf(db)
248
+ const chosen: SearchProviders = {
249
+ backoffice: providers.backoffice ?? base.backoffice,
250
+ site: providers.site ?? base.site,
251
+ matchLimit: providers.matchLimit ?? base.matchLimit,
252
+ onError: providers.onError ?? base.onError,
253
+ onCapped: providers.onCapped ?? base.onCapped,
254
+ }
255
+ registered.set(db.locks, chosen)
256
+ return chosen
257
+ }
258
+
259
+ let defaultSiteSearch: (db: Db) => SiteSearchProvider = () => {
260
+ throw new Error('site search is not wired')
261
+ }
262
+
263
+ /** Set once by `site-search.ts`, which owns the site-search rows, to avoid an import cycle. */
264
+ export function setDefaultSiteSearch(make: (db: Db) => SiteSearchProvider): void {
265
+ defaultSiteSearch = make
266
+ }
267
+
268
+ const cappedOnce = new WeakSet<object>()
269
+
270
+ /**
271
+ * Backoffice search's matches for `query`, as a subquery of `node_id` and
272
+ * `score` to join: the database provider's own match, or a provider's matches
273
+ * as a table of values, at most the match limit. Undefined when the query
274
+ * holds no words.
275
+ */
276
+ export async function fullTextHits(
277
+ db: Db,
278
+ query: string,
279
+ kinds: readonly SearchKind[],
280
+ ): Promise<RawBuilder<FullTextHit> | undefined> {
281
+ if (searchTerms(query).length === 0) return undefined
282
+ const providers = searchProvidersOf(db)
283
+ const provider = providers.backoffice as Partial<DatabaseBackofficeSearch>
284
+ if (provider.sqlMatches) return provider.sqlMatches(query)
285
+ const matches = await providers.backoffice.matches(query, {
286
+ kinds,
287
+ limit: providers.matchLimit,
288
+ })
289
+ if (matches.length >= providers.matchLimit && !cappedOnce.has(providers)) {
290
+ cappedOnce.add(providers)
291
+ providers.onCapped?.()
292
+ }
293
+ // The matches as a table of values, built as every other query is.
294
+ const row = (m: { id: number; score: number }) =>
295
+ db.q.selectNoFrom([sql.lit(m.id).as('node_id'), sql.lit(m.score).as('score')])
296
+ const [first, ...rest] = matches
297
+ const table = first
298
+ ? rest.reduce((acc, m) => acc.unionAll(row(m)), row(first))
299
+ : row({ id: 0, score: 0 }).where(sql<boolean>`${sql.lit(false)}`)
300
+ return sql<FullTextHit>`(${table})`
301
+ }
302
+
303
+ /**
304
+ * Records what a provider outside the database must forget, inside the
305
+ * delete's transaction and before its rows go: each page, media item and
306
+ * member among `nodeIds`.
307
+ */
308
+ export async function recordSearchRemovals(tx: Db, nodeIds: readonly number[]): Promise<void> {
309
+ const removedAt = DbDate.toDb(new Date())
310
+ for (let i = 0; i < nodeIds.length; i += 500) {
311
+ const rows = await tx.q
312
+ .selectFrom('node')
313
+ .select(['id', 'unique_id', 'node_object_type'])
314
+ .where('id', 'in', nodeIds.slice(i, i + 500))
315
+ .where('node_object_type', 'in', Object.values(KIND_OBJECT_TYPES))
316
+ .execute()
317
+ if (rows.length === 0) continue
318
+ await tx.q
319
+ .insertInto('search_removal')
320
+ .values(
321
+ rows.map((row) => ({
322
+ node_id: Number(row.id),
323
+ node_key: String(row.unique_id).toLowerCase(),
324
+ kind: kindOf(String(row.node_object_type)) as SearchKind,
325
+ removed_at: removedAt,
326
+ })),
327
+ )
328
+ .execute()
329
+ }
330
+ }
331
+
332
+ /** One removal waiting for the providers outside the database. */
333
+ export interface SearchRemoval {
334
+ id: number
335
+ nodeId: number
336
+ key: string
337
+ kind: SearchKind
338
+ }
339
+
340
+ export async function pendingSearchRemovals(db: Db, limit: number): Promise<SearchRemoval[]> {
341
+ const rows = await db.q
342
+ .selectFrom('search_removal')
343
+ .select(['id', 'node_id', 'node_key', 'kind'])
344
+ .orderBy('id')
345
+ .limit(limit)
346
+ .execute()
347
+ return rows.map((row) => ({
348
+ id: Number(row.id),
349
+ nodeId: Number(row.node_id),
350
+ key: String(row.node_key),
351
+ kind: String(row.kind) as SearchKind,
352
+ }))
353
+ }
354
+
355
+ export async function forgetSearchRemovals(db: Db, ids: readonly number[]): Promise<void> {
356
+ if (ids.length === 0) return
357
+ await db.q
358
+ .deleteFrom('search_removal')
359
+ .where('id', 'in', [...ids])
360
+ .execute()
361
+ }
362
+
363
+ /** What a provider is told an item is, read from the node. Undefined for anything not indexed. */
364
+ export async function searchItemFor(db: Db, nodeId: number): Promise<SearchItem | undefined> {
365
+ const row = await db.q
366
+ .selectFrom('node as n')
367
+ .leftJoin('content as c', 'c.node_id', 'n.id')
368
+ .leftJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
369
+ .select(['n.id', 'n.unique_id', 'n.path', 'n.node_object_type', 'n.trashed', 'ct.alias'])
370
+ .where('n.id', '=', nodeId)
371
+ .executeTakeFirst()
372
+ const kind = row && kindOf(String(row.node_object_type))
373
+ if (!row || !kind) return undefined
374
+ return {
375
+ id: Number(row.id),
376
+ key: String(row.unique_id).toLowerCase(),
377
+ kind,
378
+ contentTypeAlias: String(row.alias ?? ''),
379
+ path: String(row.path)
380
+ .split(',')
381
+ .map(Number)
382
+ .filter((id) => id > 0),
383
+ trashed: fromDbBool(row.trashed),
384
+ }
385
+ }
@@ -3,24 +3,7 @@
3
3
  * both the index and a query go through so they meet. docs/search.md.
4
4
  */
5
5
 
6
- /**
7
- * Lowercase words without diacritics: letters and digits only, everything else
8
- * a separator. The index stores text in this form, so the full-text engines on
9
- * both dialects only ever split on spaces, and match the same way.
10
- */
11
- export function searchWords(text: string): string[] {
12
- return text
13
- .normalize('NFKD')
14
- .replace(/\p{M}+/gu, '')
15
- .toLowerCase()
16
- .split(/[^\p{L}\p{N}]+/u)
17
- .filter((word) => word.length > 0)
18
- }
19
-
20
- /** The distinct words of a query, at most a dozen: what every result must hold by prefix. */
21
- export function searchTerms(query: string): string[] {
22
- return [...new Set(searchWords(query))].slice(0, 12)
23
- }
6
+ export { searchTerms, searchWords } from '@crombolo/core'
24
7
 
25
8
  const IDENTIFIER =
26
9
  /^(?:umb:\/\/\S+|\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?)$/i
package/src/search.ts CHANGED
@@ -3,15 +3,31 @@
3
3
  * queued item into rows, and the two indexes the Examine dashboard shows. The
4
4
  * same indexer writes a page's site-search rows (`site-search.ts`). docs/search.md.
5
5
  */
6
- import { ObjectTypes } from '@crombolo/core'
6
+ import {
7
+ type BackofficeIndexName,
8
+ type BackofficeSearchEntry,
9
+ type BackofficeSearchHit,
10
+ type BackofficeSearchProvider,
11
+ ObjectTypes,
12
+ type SiteSearchEntry,
13
+ type SiteSearchProvider,
14
+ } from '@crombolo/core'
7
15
  import type { Db } from './database.ts'
8
- import { DbDate, fromDbBool } from './dialect.ts'
16
+ import { fromDbBool } from './dialect.ts'
9
17
  import { type Expression, now, rowLock } from './query.ts'
10
- import { searchTerms, searchWords, type UnsearchableProperty, valueText } from './search-text.ts'
11
- import { siteEntriesFor, writeSiteEntries } from './site-search.ts'
18
+ import {
19
+ forgetSearchRemovals,
20
+ isInDatabase,
21
+ pendingSearchRemovals,
22
+ type SearchProviders,
23
+ searchItemFor,
24
+ searchProvidersOf,
25
+ } from './search-providers.ts'
26
+ import { searchWords, type UnsearchableProperty, valueText } from './search-text.ts'
27
+ import { siteEntriesFor } from './site-search.ts'
12
28
 
13
29
  /** Umbraco's names for the two backoffice indexes, which the dashboard shows. */
14
- export type SearchIndexName = 'InternalIndex' | 'MembersIndex'
30
+ export type SearchIndexName = BackofficeIndexName
15
31
 
16
32
  export interface SearchIndexDefinition {
17
33
  name: SearchIndexName
@@ -108,12 +124,7 @@ export async function queueEverythingForSearch(db: Db): Promise<void> {
108
124
  }
109
125
 
110
126
  /** One row of `search_document`: an item in one culture, '' when invariant. */
111
- export interface SearchEntry {
112
- culture: string
113
- name: string
114
- body: string
115
- fields: Record<string, string[]>
116
- }
127
+ export type SearchEntry = BackofficeSearchEntry
117
128
 
118
129
  export interface SearchIndexStats {
119
130
  documentCount: number
@@ -122,11 +133,7 @@ export interface SearchIndexStats {
122
133
  pending: number
123
134
  }
124
135
 
125
- export interface SearchHit {
126
- key: string
127
- score: number
128
- fields: Array<{ name: string; values: string[] }>
129
- }
136
+ export type SearchHit = BackofficeSearchHit
130
137
 
131
138
  export class SearchIndex {
132
139
  #db: Db
@@ -148,8 +155,18 @@ export class SearchIndex {
148
155
  * indexed. Each item is its own transaction, claimed by locking its queue row:
149
156
  * a second indexer passes over it, and a write queueing it again bumps the
150
157
  * generation, so the row outlives this run and the item is indexed once more.
158
+ *
159
+ * A provider outside the database (story 273) is written first, outside the
160
+ * transaction, so a slow service holds no write lock; if it fails, the row
161
+ * stays and the item is tried again on the next run.
151
162
  */
152
163
  async indexQueued(limit = 200): Promise<number> {
164
+ const providers = searchProvidersOf(this.#db)
165
+ const outside = {
166
+ backoffice: isInDatabase(providers.backoffice) ? undefined : providers.backoffice,
167
+ site: isInDatabase(providers.site) ? undefined : providers.site,
168
+ }
169
+ await this.#forgetRemoved(providers, outside)
153
170
  const queued = await this.#db.q
154
171
  .selectFrom('search_index_queue')
155
172
  .select(['node_id', 'generation'])
@@ -161,6 +178,18 @@ export class SearchIndex {
161
178
  for (const row of queued) {
162
179
  const nodeId = Number(row.node_id)
163
180
  const generation = Number(row.generation)
181
+ if (outside.backoffice || outside.site) {
182
+ const item = await searchItemFor(this.#db, nodeId)
183
+ try {
184
+ if (item && outside.backoffice)
185
+ await outside.backoffice.write(item, await entriesFor(this.#db, nodeId))
186
+ if (item && outside.site && item.kind === 'document')
187
+ await outside.site.write(item, await siteEntriesFor(this.#db, nodeId))
188
+ } catch (error) {
189
+ providers.onError?.(error, { provider: outsideName(outside), key: item?.key })
190
+ continue
191
+ }
192
+ }
164
193
  const done = await this.#db.transaction(async (tx) => {
165
194
  const claimed = await tx.q
166
195
  .selectFrom('search_index_queue')
@@ -170,8 +199,11 @@ export class SearchIndex {
170
199
  .$call(rowLock(tx, 'update skip locked'))
171
200
  .execute()
172
201
  if (claimed.length === 0) return false
173
- await writeEntries(tx, nodeId, await entriesFor(tx, nodeId))
174
- await writeSiteEntries(tx, nodeId, await siteEntriesFor(tx, nodeId))
202
+ const item = { id: nodeId }
203
+ if (isInDatabase<SearchEntry>(providers.backoffice))
204
+ await providers.backoffice.writeIn(tx, item, await entriesFor(tx, nodeId))
205
+ if (isInDatabase<SiteSearchEntry>(providers.site))
206
+ await providers.site.writeIn(tx, item, await siteEntriesFor(tx, nodeId))
175
207
  await tx.q
176
208
  .deleteFrom('search_index_queue')
177
209
  .where('node_id', '=', nodeId)
@@ -184,6 +216,30 @@ export class SearchIndex {
184
216
  return indexed
185
217
  }
186
218
 
219
+ /** Tells the providers outside the database what was deleted; the database cascaded already. */
220
+ async #forgetRemoved(
221
+ providers: SearchProviders,
222
+ outside: { backoffice?: BackofficeSearchProvider; site?: SiteSearchProvider },
223
+ ): Promise<void> {
224
+ for (;;) {
225
+ const removals = await pendingSearchRemovals(this.#db, 200)
226
+ if (removals.length === 0) return
227
+ const done: number[] = []
228
+ for (const removal of removals) {
229
+ const item = { id: removal.nodeId, key: removal.key, kind: removal.kind }
230
+ try {
231
+ await outside.backoffice?.remove(item)
232
+ if (removal.kind === 'document') await outside.site?.remove(item)
233
+ done.push(removal.id)
234
+ } catch (error) {
235
+ providers.onError?.(error, { provider: outsideName(outside), key: removal.key })
236
+ }
237
+ }
238
+ await forgetSearchRemovals(this.#db, done)
239
+ if (done.length < removals.length) return
240
+ }
241
+ }
242
+
187
243
  /** Indexes until nothing is queued. For tests and the command line. */
188
244
  async indexAll(): Promise<number> {
189
245
  let total = 0
@@ -194,33 +250,26 @@ export class SearchIndex {
194
250
  }
195
251
  }
196
252
 
197
- /** Queues every item the index covers; the index keeps answering meanwhile. */
253
+ /**
254
+ * Queues every item the index covers. The database index keeps answering
255
+ * meanwhile; a provider that clears first starts again from nothing.
256
+ */
198
257
  async rebuild(index: SearchIndexDefinition): Promise<void> {
258
+ const providers = searchProvidersOf(this.#db)
259
+ await providers.backoffice.clear?.(index.name)
260
+ if (index.name === 'InternalIndex') await providers.site.clear?.()
199
261
  await enqueue(this.#db, nodesOfTypes(this.#db, index.objectTypes))
200
262
  }
201
263
 
202
264
  async stats(index: SearchIndexDefinition): Promise<SearchIndexStats> {
203
- const types = index.objectTypes
204
- const documents = await this.#db.q
205
- .selectFrom('search_document as sd')
206
- .innerJoin('node as n', 'n.id', 'sd.node_id')
207
- .select((eb) => [
208
- eb.fn.count('sd.node_id').distinct().as('n'),
209
- eb.fn.max('sd.field_count').as('fields'),
210
- ])
211
- .where('n.node_object_type', 'in', types)
212
- .executeTakeFirst()
265
+ const stored = await searchProvidersOf(this.#db).backoffice.stats(index.name)
213
266
  const pending = await this.#db.q
214
267
  .selectFrom('search_index_queue as q')
215
268
  .innerJoin('node as n', 'n.id', 'q.node_id')
216
269
  .select((eb) => eb.fn.countAll().as('n'))
217
- .where('n.node_object_type', 'in', types)
270
+ .where('n.node_object_type', 'in', index.objectTypes)
218
271
  .executeTakeFirst()
219
- return {
220
- documentCount: Number(documents?.n ?? 0),
221
- fieldCount: Number(documents?.fields ?? 0),
222
- pending: Number(pending?.n ?? 0),
223
- }
272
+ return { ...stored, pending: Number(pending?.n ?? 0) }
224
273
  }
225
274
 
226
275
  /** The Examine dashboard's search: every stored field of each matching item, best first. */
@@ -229,63 +278,28 @@ export class SearchIndex {
229
278
  term: string,
230
279
  paging: { skip: number; take: number },
231
280
  ): Promise<{ total: number; items: SearchHit[] }> {
232
- const terms = searchTerms(term)
233
- if (terms.length === 0) return { total: 0, items: [] }
234
- const types = index.objectTypes
235
- const dialect = this.#db.dialect
236
- const hits = this.#db.q
237
- .selectFrom(dialect.fullTextMatches(dialect.fullTextQuery(terms)).as('h'))
238
- .innerJoin('node as n', 'n.id', 'h.node_id')
239
- .where('n.node_object_type', 'in', types)
240
- const count = await hits.select((eb) => eb.fn.countAll().as('n')).executeTakeFirst()
241
- const rows = await hits
242
- .select(['n.id', 'n.unique_id as key', 'h.score'])
243
- .orderBy('h.score', 'desc')
244
- .orderBy('n.id')
245
- .limit(paging.take)
246
- .offset(paging.skip)
247
- .execute()
248
- const items: SearchHit[] = []
249
- for (const row of rows) {
250
- const stored = await this.#db.q
251
- .selectFrom('search_document')
252
- .select('fields')
253
- .where('node_id', '=', Number(row.id))
254
- .orderBy('culture')
255
- .execute()
256
- const merged = new Map<string, string[]>()
257
- for (const entry of stored)
258
- for (const [name, values] of Object.entries(
259
- JSON.parse(entry.fields) as Record<string, string[]>,
260
- ))
261
- merged.set(name, [...new Set([...(merged.get(name) ?? []), ...values])])
262
- items.push({
263
- key: String(row.key),
264
- score: Number(row.score),
265
- fields: [...merged].map(([name, values]) => ({ name, values })),
266
- })
281
+ const found = await searchProvidersOf(this.#db).backoffice.query(index.name, term, paging)
282
+ // A provider outside the database may hold what was deleted since it last heard.
283
+ const keys = found.items.map((hit) => hit.key.toLowerCase())
284
+ if (keys.length === 0) return found
285
+ const present = new Set(
286
+ (
287
+ await this.#db.q
288
+ .selectFrom('node')
289
+ .select('unique_id')
290
+ .where('unique_id', 'in', keys)
291
+ .execute()
292
+ ).map((row) => String(row.unique_id).toLowerCase()),
293
+ )
294
+ return {
295
+ total: found.total,
296
+ items: found.items.filter((hit) => present.has(hit.key.toLowerCase())),
267
297
  }
268
- return { total: Number(count?.n ?? 0), items }
269
298
  }
270
299
  }
271
300
 
272
- async function writeEntries(tx: Db, nodeId: number, entries: readonly SearchEntry[]) {
273
- await tx.q.deleteFrom('search_document').where('node_id', '=', nodeId).execute()
274
- const indexedAt = DbDate.toDb(new Date())
275
- for (const entry of entries)
276
- await tx.q
277
- .insertInto('search_document')
278
- .values({
279
- node_id: nodeId,
280
- culture: entry.culture,
281
- name: entry.name,
282
- body: entry.body,
283
- fields: JSON.stringify(entry.fields),
284
- field_count: Object.keys(entry.fields).length,
285
- indexed_at: indexedAt,
286
- })
287
- .execute()
288
- }
301
+ const outsideName = (outside: { backoffice?: { name: string }; site?: { name: string } }) =>
302
+ [outside.backoffice?.name, outside.site?.name].filter(Boolean).join(', ')
289
303
 
290
304
  const folded = (texts: readonly string[]) => texts.flatMap(searchWords).join(' ')
291
305
 
@@ -4,49 +4,26 @@
4
4
  * that writes backoffice search rows writes these too (`search.ts`), from the
5
5
  * same queue. docs/search.md.
6
6
  */
7
- import { ObjectTypes, type SiteSearchLevel } from '@crombolo/core'
7
+ import {
8
+ ObjectTypes,
9
+ type SiteSearchEntry,
10
+ type SiteSearchHit,
11
+ type SiteSearchLevel,
12
+ type SiteSearchQuery,
13
+ type SiteSearchText,
14
+ } from '@crombolo/core'
8
15
  import type { Db } from './database.ts'
9
16
  import { DbDate, fromDbBool } from './dialect.ts'
10
17
  import { sql } from './query.ts'
11
18
  import { publishedValueRows } from './repositories/documents.ts'
12
19
  import { hiddenElementProperties } from './search.ts'
20
+ import { databaseSiteSearch, setDefaultSiteSearch } from './search-providers.ts'
13
21
  import { searchTerms, searchWords, valueText } from './search-text.ts'
14
22
 
15
- /** A page's text as written, by weight: what an excerpt is cut from. */
16
- export interface SiteSearchText {
17
- name: string
18
- high: string[]
19
- normal: string[]
20
- low: string[]
21
- }
22
-
23
- /** One row of `site_search_document`: a page in one culture, '' when invariant. */
24
- export interface SiteSearchEntry {
25
- culture: string
26
- text: SiteSearchText
27
- }
23
+ export type { SiteSearchEntry, SiteSearchHit, SiteSearchText } from '@crombolo/core'
28
24
 
29
- export interface SiteSearchOptions {
30
- /** The culture searched, lowercase; an invariant page matches every culture. */
31
- culture: string
32
- /** Content type aliases; every searchable type when empty or absent. */
33
- types?: readonly string[]
34
- skip: number
35
- take: number
36
- /**
37
- * Protected nodes, by id, that the person searching may not open and may:
38
- * `branchAccess` in `@crombolo/core`. A page is left out when the nearest
39
- * protected node on its path is denied.
40
- */
41
- access?: { denied: readonly number[]; allowed: readonly number[] }
42
- }
43
-
44
- export interface SiteSearchHit {
45
- key: string
46
- culture: string
47
- score: number
48
- text: SiteSearchText
49
- }
25
+ /** A site search over the database (`databaseSiteSearch`). */
26
+ export type SiteSearchOptions = SiteSearchQuery
50
27
 
51
28
  const LEVELS: readonly SiteSearchLevel[] = ['high', 'normal', 'low']
52
29
 
@@ -288,3 +265,10 @@ export class SiteSearch {
288
265
  }
289
266
  }
290
267
  }
268
+
269
+ setDefaultSiteSearch((db) =>
270
+ databaseSiteSearch(db, {
271
+ write: writeSiteEntries,
272
+ query: (on, query, options) => new SiteSearch(on).query(query, options),
273
+ }),
274
+ )
package/src/tables.gen.ts CHANGED
@@ -687,6 +687,13 @@ export interface CoreTables {
687
687
  node_id: Generated<number>
688
688
  queued_at: Timestamp
689
689
  }
690
+ search_removal: {
691
+ id: Generated<number>
692
+ kind: string
693
+ node_id: number
694
+ node_key: string
695
+ removed_at: Timestamp
696
+ }
690
697
  server: {
691
698
  crombolo_version: string | null
692
699
  last_seen: Timestamp