@softistx/drizzle-meilisearch 0.0.0-stage → 0.3.2

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.
@@ -0,0 +1,304 @@
1
+ # Wiring a sync
2
+
3
+ A sync is the pairing of one PostgreSQL table with one Meilisearch index:
4
+ `createSearchSync` describes it, and the methods it gives back do the work.
5
+
6
+ ```ts
7
+ import { createRepository } from '@softistx/drizzle/pg';
8
+ import { bindIndex } from '@softistx/meilisearch';
9
+ import { createSearchSync } from '@softistx/drizzle-meilisearch';
10
+ import { db, meili } from './clients'; // a Drizzle db, an SDK client
11
+ import { articles, articleIndex } from './search';
12
+
13
+ export const articleRepository = createRepository(db, articles);
14
+
15
+ export const articleSearch = createSearchSync({
16
+ repository: articleRepository,
17
+ index: bindIndex(meili, articleIndex),
18
+ toIndexId: (article) => article.id,
19
+ transform: (article) =>
20
+ article.draft ? null : { id: article.id, title: article.title },
21
+ });
22
+ ```
23
+
24
+ `createSearchSync` **does no I/O**: it checks its options, resolves the
25
+ defaults, and gives back an object. Nothing reaches PostgreSQL or Meilisearch
26
+ until [a write call](indexing-writes.md) or [`reindexAll`](reindex.md).
27
+
28
+ ## The two definitions
29
+
30
+ The table is declared with Drizzle and `@softistx/drizzle`'s column helpers, the
31
+ index with `@softistx/meilisearch`. Neither knows about this package.
32
+
33
+ ```ts
34
+ import { id, softDelete, timestamps } from '@softistx/drizzle/pg';
35
+ import { defineIndex } from '@softistx/meilisearch';
36
+ import { boolean, pgTable, text } from 'drizzle-orm/pg-core';
37
+
38
+ export const articles = pgTable('articles', {
39
+ id: id(), // uuid primary key default gen_random_uuid()
40
+ title: text('title').notNull(),
41
+ draft: boolean('draft').notNull().default(false),
42
+ ...timestamps(), // createdAt, updatedAt
43
+ ...softDelete(), // deletedAt
44
+ });
45
+
46
+ export interface ArticleHit {
47
+ id: string;
48
+ title: string;
49
+ }
50
+
51
+ export const articleIndex = defineIndex<ArticleHit>()({
52
+ uid: 'articles',
53
+ primaryKey: 'id',
54
+ settings: { searchableAttributes: ['title'] },
55
+ });
56
+ ```
57
+
58
+ The index's **settings** are `@softistx/meilisearch`'s to apply, as a startup or
59
+ deployment step:
60
+
61
+ ```ts
62
+ const index = bindIndex(meili, articleIndex);
63
+ await index.sync(); // creates the index and applies its settings
64
+ ```
65
+
66
+ Worth doing before anything else: Meilisearch creates an index on a write of
67
+ documents but not on a delete, so a `remove(...)` on an index nothing has
68
+ written to yet fails. See [Indexing after a write](indexing-writes.md).
69
+
70
+ ## The transform
71
+
72
+ It takes the table's row — `Row<typeof articles>`, every column, `deletedAt`
73
+ included — and gives the index's document, typed by its definition. `null`
74
+ keeps a row **out** of the index, and takes it out if it was in.
75
+
76
+ ```ts
77
+ import type { Transform } from '@softistx/drizzle-meilisearch';
78
+
79
+ export const toHit: Transform<typeof articles, typeof articleIndex> = (
80
+ article,
81
+ ) => (article.draft ? null : { id: article.id, title: article.title });
82
+ ```
83
+
84
+ It may be `async` — the type allows a promise — which is how a document that
85
+ needs another read is built:
86
+
87
+ ```ts
88
+ createSearchSync({
89
+ repository: articleRepository,
90
+ index,
91
+ toIndexId: (article) => article.id,
92
+ transform: async (article) => {
93
+ if (article.draft) return null;
94
+ const tags = await tagRepository.findMany({
95
+ where: { articleId: article.id },
96
+ });
97
+ return {
98
+ id: article.id,
99
+ title: `${article.title} ${tags.map((tag) => tag.name).join(' ')}`,
100
+ };
101
+ },
102
+ });
103
+ ```
104
+
105
+ A write to that other table does not reach the index by itself; only a call on
106
+ this sync does.
107
+
108
+ The document must carry the row's **index id** under the index's primary key.
109
+ One under another id could never be taken out again, so it is refused with
110
+ `ID_MISMATCH`. Anything that is neither a document nor `null` — a string, a
111
+ number, an array — is refused with `NOT_A_DOCUMENT`, and the message reports
112
+ its shape rather than its value.
113
+
114
+ ## `toIndexId` is required
115
+
116
+ ```ts
117
+ toIndexId: (article) => article.id,
118
+ ```
119
+
120
+ The MongoDB bridge defaults this to `String`, because every document there has
121
+ an `_id`. Here nothing could be defaulted to: Drizzle 1.0's column types do
122
+ not carry `.primaryKey()`, so neither the repository nor the table can say
123
+ which column holds the id — `@softistx/drizzle`'s own `PrimaryKeyOf` falls back to
124
+ the key `id` for exactly that reason. One line per sync says it outright, and
125
+ says it where the index's own id type can check it:
126
+
127
+ ```ts
128
+ import { bindIndex, defineIndex } from '@softistx/meilisearch';
129
+ import { createRepository } from '@softistx/drizzle/pg';
130
+ import { integer, pgTable, text } from 'drizzle-orm/pg-core';
131
+
132
+ const counters = pgTable('counters', {
133
+ id: integer('id').primaryKey(),
134
+ label: text('label').notNull(),
135
+ });
136
+
137
+ const counterIndex = bindIndex(
138
+ meili,
139
+ defineIndex<{ n: number; label: string }>()({
140
+ uid: 'counters',
141
+ primaryKey: 'n',
142
+ settings: {},
143
+ }),
144
+ );
145
+
146
+ createSearchSync({
147
+ repository: createRepository(db, counters),
148
+ index: counterIndex,
149
+ toIndexId: (counter) => counter.id, // a number, as the index's ids are
150
+ transform: (counter) => ({ n: counter.id, label: counter.label }),
151
+ });
152
+ ```
153
+
154
+ The index's id type checks it. Leaving `toIndexId` out, or giving another
155
+ type than the index's ids, does not compile:
156
+
157
+ ```ts
158
+ // @ts-expect-error toIndexId is required: no column is known to be the id
159
+ createSearchSync({ repository, index, transform: () => null });
160
+
161
+ createSearchSync({
162
+ repository: createRepository(db, counters),
163
+ index: counterIndex,
164
+ // @ts-expect-error the index's id is a number
165
+ toIndexId: (counter) => String(counter.id),
166
+ transform: (counter) => ({ n: counter.id, label: counter.label }),
167
+ });
168
+ ```
169
+
170
+ The README lists [what does not compile](../../README.md#what-does-not-compile);
171
+ every line of it is a `@ts-expect-error` case in `test/types/search-sync.ts`.
172
+
173
+ ## Options
174
+
175
+ | Option | Type | Default | Effect |
176
+ | --- | --- | --- | --- |
177
+ | `repository` | `SyncRepository<TTable>` | — | Where the rows are: from `createRepository` |
178
+ | `index` | `TypedIndex<I>` | — | Where they go: from `bindIndex` |
179
+ | `transform` | `Transform<TTable, I>` | — | The row as the index holds it, or `null` to keep it out |
180
+ | `toIndexId` | `ToIndexId<TTable, I>` | — | The index id of a row. Required |
181
+ | `name` | `string` | `` `${tableName}:${index.uid}` `` | What this sync is called in its errors |
182
+ | `batchSize` | `number` | `500` | Documents, or ids, sent to Meilisearch at once |
183
+ | `pageSize` | `number` | `100` | Rows `reindexAll` reads per page; above the repository's `maxPageSize`, lowered to it |
184
+
185
+ ### `repository`
186
+
187
+ Anything with the table and `paginateByCursor` fits — which a `Repository`
188
+ from `createRepository` is, and so is one narrowed by `with(tx)`. It is typed
189
+ as its own shape rather than `Repository<TTable, …>`, whose other parameters
190
+ describe the primary key and the soft delete, neither of which this package
191
+ reads.
192
+
193
+ ```ts
194
+ interface SyncRepository<TTable extends PgTable> {
195
+ readonly table: TTable;
196
+ paginateByCursor(options?: {
197
+ after?: string | null | undefined;
198
+ limit?: number;
199
+ }): Promise<CursorPage<Row<TTable>>>;
200
+ }
201
+ ```
202
+
203
+ The sync reads the repository only in `reindexAll`; the write calls take the
204
+ rows you hand them.
205
+
206
+ ### `name`
207
+
208
+ `'<table>:<index uid>'` unless you say otherwise — `'articles:articles'` for
209
+ the table above. It is what the errors carry, as `error.sync`, and what makes
210
+ two syncs over one table distinguishable in a log:
211
+
212
+ ```ts
213
+ createSearchSync({ …, name: 'articles:public' }).name; // 'articles:public'
214
+ ```
215
+
216
+ ### `batchSize` and `pageSize`
217
+
218
+ `batchSize` splits what goes to Meilisearch in one task — documents added, or
219
+ ids deleted. `pageSize` is how many rows `reindexAll` reads at a time, and can
220
+ be overridden per call. Both must be whole numbers above zero, or
221
+ `createSearchSync` throws a `TypeError` before anything runs:
222
+
223
+ ```ts
224
+ createSearchSync({ …, batchSize: 0 });
225
+ // TypeError: createSearchSync: batchSize must be a whole number above 0, not 0
226
+ ```
227
+
228
+ The same goes for an empty `name`, a `transform` that is not a function, and a
229
+ missing `toIndexId`:
230
+
231
+ ```ts
232
+ createSearchSync({ …, toIndexId: undefined });
233
+ // TypeError: createSearchSync: toIndexId must be a function
234
+ ```
235
+
236
+ ## In an application
237
+
238
+ The sync sits beside the repository it mirrors, and each route that writes
239
+ calls it once:
240
+
241
+ ```ts
242
+ import { Hono } from 'hono';
243
+ import { articleRepository, articleSearch } from './search/articles';
244
+
245
+ export const app = new Hono()
246
+ .post('/articles', async (c) => {
247
+ const body = await c.req.json<{ title: string }>();
248
+ const article = await articleRepository.create({ title: body.title });
249
+ await articleSearch.indexRow(article); // enqueued, not awaited by Meilisearch
250
+ return c.json(article, 201);
251
+ })
252
+ .delete('/articles/:id', async (c) => {
253
+ const deleted = await articleRepository.delete(c.req.param('id'));
254
+ await articleSearch.removeRow(deleted);
255
+ return c.body(null, 204);
256
+ });
257
+ ```
258
+
259
+ And a script fills the index, once, at deployment:
260
+
261
+ ```ts
262
+ await index.sync();
263
+ const report = await articleSearch.reindexAll();
264
+ console.log(`${articleSearch.name}:`, report);
265
+ ```
266
+
267
+ ## Signatures
268
+
269
+ ```ts
270
+ function createSearchSync<TTable extends PgTable, I extends AnyIndexDefinition>(
271
+ options: SearchSyncOptions<TTable, I>,
272
+ ): SearchSync<TTable, I>;
273
+
274
+ type Transform<TTable, I> = (
275
+ row: Row<TTable>,
276
+ ) => DocumentOf<I> | null | Promise<DocumentOf<I> | null>;
277
+
278
+ type ToIndexId<TTable, I> = (row: Row<TTable>) => IdOf<I>;
279
+
280
+ interface SearchSync<TTable extends PgTable, I extends AnyIndexDefinition> {
281
+ readonly name: string;
282
+ reindexAll(options?: ReindexOptions): Promise<ReindexReport>;
283
+ indexRow(row: Row<TTable>, options?: IndexWriteOptions): Promise<void>;
284
+ indexRows(rows: readonly Row<TTable>[], options?: IndexWriteOptions): Promise<void>;
285
+ removeRow(row: Row<TTable>, options?: IndexWriteOptions): Promise<void>;
286
+ remove(id: IdOf<I>, options?: IndexWriteOptions): Promise<void>;
287
+ removeMany(ids: readonly IdOf<I>[], options?: IndexWriteOptions): Promise<void>;
288
+ }
289
+ ```
290
+
291
+ `Row` is `@softistx/drizzle`'s, `DocumentOf` and `IdOf` are
292
+ `@softistx/meilisearch`'s. The package exports one function, `createSearchSync`;
293
+ one class, `SearchSyncError`; and nine types — `SearchSync`,
294
+ `SearchSyncOptions`, `SyncRepository`, `Transform`, `ToIndexId`,
295
+ `IndexWriteOptions`, `ReindexReport`, `SearchSyncErrorCode` and
296
+ `SearchSyncErrorOptions`. The [API section](../../README.md#api) of the
297
+ README has each of them in one table.
298
+
299
+ ## Next
300
+
301
+ - [Indexing after a write](indexing-writes.md) — the five write calls and
302
+ `wait`.
303
+ - [Reindexing](reindex.md) — the full fill, and what it removes.
304
+ - [Troubleshooting](../troubleshooting.md) — the errors, by their message.
@@ -0,0 +1,87 @@
1
+ # Roadmap
2
+
3
+ Where `@softistx/drizzle-meilisearch` is going. A direction, not a commitment: the
4
+ version an item shipped in is the only number on this page.
5
+
6
+ The scope is narrow on purpose. This package removes the collage around a
7
+ manual synchronisation — the transform, the index id, the batching, the delete
8
+ of a row that stopped qualifying — and leaves the decision of *when* to index
9
+ to the application, which already knows: it just wrote the row. **Not planned**
10
+ below is where that line is drawn, and why.
11
+
12
+ ## Now
13
+
14
+ _Nothing in progress._
15
+
16
+ ## Next
17
+
18
+ _Nothing queued._
19
+
20
+ ## Later
21
+
22
+ - **A source that is not a repository** — `SyncRepository` is already written
23
+ as its own shape, `table` plus `paginateByCursor`, rather than as
24
+ `Repository<TTable>`, so anything that pages rows by cursor nearly fits
25
+ today; `table` is read only to name the sync. Accepting a paging function,
26
+ with `name` given, would let a sync feed an index from a filtered or joined
27
+ query instead of a whole table.
28
+
29
+ ## Not planned
30
+
31
+ - **Following the table's changes, a `start()` and a resume point** — the one
32
+ that matters. `@softistx/mongo-meilisearch` follows a MongoDB change stream and
33
+ records where it stopped; PostgreSQL offers nothing equivalent a library
34
+ could read without owning the deployment. Logical replication wants a
35
+ replication slot, a publication, `wal_level=logical` and a connection that
36
+ is not the pooled one the application uses; `LISTEN`/`NOTIFY` wants a trigger
37
+ per table, is not durable, and drops everything sent while nobody was
38
+ listening. So there is no change feed here, and none pretended: index after
39
+ the write, with `indexRow` or `indexRows`.
40
+ - **A stored position, and `state()`** — there is nothing to resume from,
41
+ because nothing is followed. `reindexAll` is the way back to a correct index.
42
+ - **Reading the primary key from the table, so `toIndexId` could be optional**
43
+ — Drizzle 1.0's column types do not carry `.primaryKey()`, which is why
44
+ `@softistx/drizzle`'s own `PrimaryKeyOf` falls back to the key `id`. A guessed
45
+ index id writes documents under an id nothing can take out again; one line
46
+ per sync says it outright, and says it where the index's id type can check
47
+ it.
48
+ - **A repository wrapper whose writes index themselves** — a `create` that
49
+ also sends the document reads well until it throws: the row is committed,
50
+ the index write is not, and the caller is handed an error for work it did
51
+ not ask for, at a point it cannot undo. It would also hide when the index is
52
+ written, which is the single decision this package deliberately leaves with
53
+ the application.
54
+ - **Indexing inside the transaction that wrote the row** — a Meilisearch write
55
+ is not part of a PostgreSQL transaction, and a rollback cannot undo it: the
56
+ index would hold a row the table never kept. Index after the transaction
57
+ commits.
58
+ - **Several tables into one index** — one sync is one repository and one index.
59
+ `reindexAll` removes every document the repository did not give it, whoever
60
+ wrote it, so two syncs sharing an index would each take out what the other
61
+ added.
62
+
63
+ ## Shipped
64
+
65
+ - **A reindex that says where it is** — `reindexAll({ onPage })` calls back
66
+ after each page is applied with the running `pages`, `indexed` and
67
+ `skipped`, so a deployment step or a script reports progress on a large
68
+ table instead of a long silence; a callback that throws stops the reindex,
69
+ which is also how to stop one on purpose — 0.2.0.
70
+ - **First release** — `createSearchSync`, which builds nothing and opens
71
+ nothing: the repository and the index are already bound, and no call reaches
72
+ PostgreSQL or Meilisearch until a method is used. `reindexAll` pages every
73
+ live row through the transform, sends it in batches, and then takes out the
74
+ documents the index holds and the table no longer gives it — soft-deleted
75
+ rows included — reporting `indexed`, `skipped` and `removed`. `indexRow` and
76
+ `indexRows` after a write — the list keyed by index id, last state winning, so
77
+ two states of one row in a call cannot have the add undone by the delete —
78
+ `removeRow`, `remove` and `removeMany` for a row that is gone, all with
79
+ `wait` defaulting to `false`, so a request that has just written a row does
80
+ not hold its response open for Meilisearch. The
81
+ transform is typed by both the table's row and the index's document, and
82
+ `null` keeps a row out of the index and takes it out if it was in;
83
+ `SearchSyncError` carries the sync's name with `ID_MISMATCH`,
84
+ `NOT_A_DOCUMENT` and `FAILED` — 0.1.0.
85
+
86
+ Everything released is in [`CHANGELOG.md`](https://github.com/softistx/data/blob/develop/packages/drizzle-meilisearch/CHANGELOG.md) — it is not in
87
+ the published package, only in the repository.