@crombolo/data 0.59.0 → 0.61.0

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.59.0",
3
+ "version": "0.61.0",
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",
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/core": "0.59.0",
32
+ "@crombolo/core": "0.61.0",
33
33
  "kysely": "0.29.6"
34
34
  }
35
35
  }
@@ -18,6 +18,9 @@ export const SITE_OWNER = 'site'
18
18
  /** Table and column names, as an owner writes them. */
19
19
  export const LOGICAL_NAME = /^[a-z][a-z0-9_]*$/
20
20
 
21
+ /** An extension's id, as `crombolo.id` is read (`BUNDLE_ID` in `@crombolo/backoffice-host`). */
22
+ export const EXTENSION_ID = /^[a-z][a-z0-9-]{1,38}$/
23
+
21
24
  const underscored = (id: string): string => id.replaceAll('-', '_')
22
25
 
23
26
  /** The owner's Postgres schema: `site`, or `bundle_<id>` with the id's hyphens as underscores. */
@@ -14,7 +14,7 @@ import { connect, type Db } from '../database.ts'
14
14
  import { Locks } from '../locks.ts'
15
15
  import { deleteKeyValue, readKeyValue, writeKeyValue } from '../migrations.ts'
16
16
  import { queryFor } from '../query.ts'
17
- import { ownerFile, roleComment, roleName, schemaName } from './names.ts'
17
+ import { EXTENSION_ID, ownerFile, roleComment, roleName, SITE_OWNER, schemaName } from './names.ts'
18
18
 
19
19
  /** Where one owner's tables are. */
20
20
  export interface OwnerPlace {
@@ -82,20 +82,58 @@ export class OwnerSchemaTakenError extends Error {
82
82
 
83
83
  const literal = (value: string): string => `'${value.replaceAll("'", "''")}'`
84
84
 
85
- /** The statements that make an owner's role and schema, as an operator would run them. */
86
- export function ownerSetupStatements(
87
- db: Db,
88
- place: { role: string; schema: string },
89
- database: string,
90
- grantee: string,
91
- ): string[] {
92
- const q = (id: string) => db.dialect.quote(id)
93
- return [
94
- `CREATE ROLE ${q(place.role)} NOLOGIN;`,
95
- `COMMENT ON ROLE ${q(place.role)} IS ${literal(roleComment(database))};`,
96
- `GRANT ${q(place.role)} TO ${q(grantee)};`,
97
- `CREATE SCHEMA IF NOT EXISTS ${q(place.schema)} AUTHORIZATION ${q(place.role)};`,
98
- ]
85
+ const quote = (id: string): string => `"${id.replaceAll('"', '""')}"`
86
+
87
+ /** What a host provisioning an owner itself needs to know (story 321). */
88
+ export interface OwnerSetupInput {
89
+ /** The site name the CMS will boot with. */
90
+ siteName: string
91
+ /** `site`, or an extension's id. */
92
+ owner: string
93
+ /** The Postgres database's name. */
94
+ database: string
95
+ /** The site's database user, which is granted the role. */
96
+ grantee: string
97
+ }
98
+
99
+ /** An owner's role and schema, and the statements that make them. */
100
+ export interface OwnerSetup {
101
+ role: string
102
+ schema: string
103
+ comment: string
104
+ statements: string[]
105
+ }
106
+
107
+ /**
108
+ * The role, schema and statements the CMS would use for an owner, without a
109
+ * connection, so a host may make them as its own administrator before a site
110
+ * boots. A role name the database already recorded wins over this one.
111
+ */
112
+ export function ownerSetup(input: OwnerSetupInput): OwnerSetup {
113
+ if (input.owner !== SITE_OWNER && !EXTENSION_ID.test(input.owner))
114
+ throw new Error(`"${input.owner}" is neither "${SITE_OWNER}" nor an extension's id.`)
115
+ return setupFor(
116
+ roleName(input.siteName, input.owner, input.database),
117
+ input.owner,
118
+ input.database,
119
+ input.grantee,
120
+ )
121
+ }
122
+
123
+ function setupFor(role: string, owner: string, database: string, grantee: string): OwnerSetup {
124
+ const schema = schemaName(owner)
125
+ const comment = roleComment(database)
126
+ return {
127
+ role,
128
+ schema,
129
+ comment,
130
+ statements: [
131
+ `CREATE ROLE ${quote(role)} NOLOGIN;`,
132
+ `COMMENT ON ROLE ${quote(role)} IS ${literal(comment)};`,
133
+ `GRANT ${quote(role)} TO ${quote(grantee)};`,
134
+ `CREATE SCHEMA IF NOT EXISTS ${quote(schema)} AUTHORIZATION ${quote(role)};`,
135
+ ],
136
+ }
99
137
  }
100
138
 
101
139
  interface Catalogue {
@@ -169,8 +207,7 @@ export async function provisionOwner(
169
207
  const found = await catalogue(db)
170
208
  const role =
171
209
  (await readKeyValue(db, roleKey(owner))) ?? roleName(settings.siteName, owner, found.database)
172
- const place = { role, schema }
173
- const statements = ownerSetupStatements(db, place, found.database, found.user)
210
+ const { statements } = setupFor(role, owner, found.database, found.user)
174
211
  const q = (id: string) => db.dialect.quote(id)
175
212
  const k = queryFor(db)
176
213
 
@@ -0,0 +1,198 @@
1
+ /**
2
+ * What each extension did (story 327): its writes, requests out, rows written,
3
+ * refusals, calls and screens one row each, and its reads counted per minute.
4
+ * Read by Installed's Activity view, newest first; pruned by the window the
5
+ * site keeps. docs/extensions.md, "Watching one".
6
+ */
7
+ import type { Db } from './database.ts'
8
+ import { DbDate } from './dialect.ts'
9
+
10
+ export type ActivityKind = 'read' | 'write' | 'request' | 'rows' | 'call' | 'screen' | 'refused'
11
+ export const ACTIVITY_KINDS: readonly ActivityKind[] = [
12
+ 'read',
13
+ 'write',
14
+ 'request',
15
+ 'rows',
16
+ 'call',
17
+ 'screen',
18
+ 'refused',
19
+ ]
20
+
21
+ export type ActivityOutcome = 'ok' | 'failed' | 'refused'
22
+
23
+ export interface ActivityInput {
24
+ extensionId: string
25
+ /** Whom it acted for; null when it acted as itself. */
26
+ personKey: string | null
27
+ personName: string | null
28
+ kind: ActivityKind
29
+ /** The area, the host, the table, or the route or screen it called. */
30
+ area: string | null
31
+ verb: string | null
32
+ entityKey: string | null
33
+ count: number
34
+ outcome: ActivityOutcome
35
+ ms: number | null
36
+ occurredAt: Date
37
+ }
38
+
39
+ export interface ActivityEntry extends ActivityInput {
40
+ id: number
41
+ }
42
+
43
+ export interface ActivityFilter {
44
+ kind?: ActivityKind
45
+ /** A person's key, or `itself` for what it did as itself. */
46
+ person?: string
47
+ since?: Date
48
+ until?: Date
49
+ }
50
+
51
+ const MAX_TEXT = 255
52
+ const clip = (value: string | null): string | null =>
53
+ value === null ? null : value.slice(0, MAX_TEXT)
54
+
55
+ export class ExtensionActivityLog {
56
+ readonly #db: Db
57
+ constructor(db: Db) {
58
+ this.#db = db
59
+ }
60
+
61
+ async record(rows: readonly ActivityInput[]): Promise<void> {
62
+ if (rows.length === 0) return
63
+ await this.#db.q
64
+ .insertInto('extension_activity')
65
+ .values(
66
+ rows.map((row) => ({
67
+ extension_id: row.extensionId,
68
+ person_key: clip(row.personKey),
69
+ person_name: clip(row.personName),
70
+ kind: row.kind,
71
+ area: clip(row.area),
72
+ verb: clip(row.verb),
73
+ entity_key: clip(row.entityKey),
74
+ count: row.count,
75
+ outcome: row.outcome,
76
+ ms: row.ms === null ? null : Math.round(row.ms),
77
+ occurred_at: DbDate.toDb(row.occurredAt),
78
+ })),
79
+ )
80
+ .execute()
81
+ }
82
+
83
+ #filtered(extensionId: string, filter: ActivityFilter) {
84
+ let query = this.#db.q.selectFrom('extension_activity').where('extension_id', '=', extensionId)
85
+ if (filter.kind) query = query.where('kind', '=', filter.kind)
86
+ if (filter.person === 'itself') query = query.where('person_key', 'is', null)
87
+ else if (filter.person) query = query.where('person_key', '=', filter.person)
88
+ if (filter.since) query = query.where('occurred_at', '>=', DbDate.toDb(filter.since))
89
+ if (filter.until) query = query.where('occurred_at', '<', DbDate.toDb(filter.until))
90
+ return query
91
+ }
92
+
93
+ /** Newest first, below `before` when given. */
94
+ async page(
95
+ extensionId: string,
96
+ filter: ActivityFilter,
97
+ cursor: { before?: number; limit: number },
98
+ ): Promise<{ items: ActivityEntry[]; next: number | null }> {
99
+ let query = this.#filtered(extensionId, filter)
100
+ if (cursor.before !== undefined) query = query.where('id', '<', cursor.before)
101
+ const rows = await query.selectAll().orderBy('id', 'desc').limit(cursor.limit).execute()
102
+ const items = rows.map(
103
+ (row): ActivityEntry => ({
104
+ id: Number(row.id),
105
+ extensionId: row.extension_id,
106
+ personKey: row.person_key ?? null,
107
+ personName: row.person_name ?? null,
108
+ kind: row.kind as ActivityKind,
109
+ area: row.area ?? null,
110
+ verb: row.verb ?? null,
111
+ entityKey: row.entity_key ?? null,
112
+ count: Number(row.count),
113
+ outcome: row.outcome as ActivityOutcome,
114
+ ms: row.ms === null || row.ms === undefined ? null : Number(row.ms),
115
+ occurredAt: DbDate.fromDb(row.occurred_at) ?? new Date(0),
116
+ }),
117
+ )
118
+ return {
119
+ items,
120
+ next: items.length === cursor.limit ? (items.at(-1)?.id ?? null) : null,
121
+ }
122
+ }
123
+
124
+ /** How many of each kind since a time, reads counted as many as were made. */
125
+ async counts(extensionId: string, since?: Date): Promise<Record<ActivityKind, number>> {
126
+ const rows = await this.#filtered(extensionId, { since })
127
+ .select((eb) => ['kind', eb.fn.sum<number | string>('count').as('total')])
128
+ .groupBy('kind')
129
+ .execute()
130
+ const out = Object.fromEntries(ACTIVITY_KINDS.map((kind) => [kind, 0])) as Record<
131
+ ActivityKind,
132
+ number
133
+ >
134
+ for (const row of rows) out[row.kind as ActivityKind] = Number(row.total ?? 0)
135
+ return out
136
+ }
137
+
138
+ /** Everyone it acted for, by the name it last recorded. */
139
+ async people(extensionId: string): Promise<Array<{ key: string; name: string }>> {
140
+ const rows = await this.#filtered(extensionId, {})
141
+ .where('person_key', 'is not', null)
142
+ .select((eb) => ['person_key', eb.fn.max('person_name').as('name')])
143
+ .groupBy('person_key')
144
+ .execute()
145
+ return rows.map((row) => ({ key: String(row.person_key), name: String(row.name ?? '') }))
146
+ }
147
+
148
+ /** Deletes what is older than `before`; how many went. Counted first, as the wrapper does not say. */
149
+ async prune(before: Date): Promise<number> {
150
+ const counted = await this.#db.q
151
+ .selectFrom('extension_activity')
152
+ .select((eb) => eb.fn.countAll().as('total'))
153
+ .where('occurred_at', '<', DbDate.toDb(before))
154
+ .executeTakeFirst()
155
+ const total = Number(counted?.total ?? 0)
156
+ if (total > 0)
157
+ await this.#db.q
158
+ .deleteFrom('extension_activity')
159
+ .where('occurred_at', '<', DbDate.toDb(before))
160
+ .execute()
161
+ return total
162
+ }
163
+
164
+ /** Keeps an extension's newest `max` rows and deletes the rest; how many went. */
165
+ async cap(extensionId: string, max: number): Promise<number> {
166
+ const edge = await this.#db.q
167
+ .selectFrom('extension_activity')
168
+ .select('id')
169
+ .where('extension_id', '=', extensionId)
170
+ .orderBy('id', 'desc')
171
+ .offset(max)
172
+ .limit(1)
173
+ .executeTakeFirst()
174
+ if (!edge) return 0
175
+ const counted = await this.#db.q
176
+ .selectFrom('extension_activity')
177
+ .select((eb) => eb.fn.countAll().as('total'))
178
+ .where('extension_id', '=', extensionId)
179
+ .where('id', '<=', Number(edge.id))
180
+ .executeTakeFirst()
181
+ await this.#db.q
182
+ .deleteFrom('extension_activity')
183
+ .where('extension_id', '=', extensionId)
184
+ .where('id', '<=', Number(edge.id))
185
+ .execute()
186
+ return Number(counted?.total ?? 0)
187
+ }
188
+
189
+ /** The extensions it has rows for, for the cap. */
190
+ async extensions(): Promise<string[]> {
191
+ const rows = await this.#db.q
192
+ .selectFrom('extension_activity')
193
+ .select('extension_id')
194
+ .distinct()
195
+ .execute()
196
+ return rows.map((row) => row.extension_id)
197
+ }
198
+ }
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ export * from './content-query.ts'
7
7
  export * from './custom-tables/index.ts'
8
8
  export * from './database.ts'
9
9
  export * from './dialect.ts'
10
+ export * from './extension-activity.ts'
10
11
  export * from './locks.ts'
11
12
  export * from './maintenance.ts'
12
13
  export * from './migrations.ts'
@@ -63,6 +64,7 @@ export * from './schema/audit-log.ts'
63
64
  export * from './schema/built-in-content-types.ts'
64
65
  export * from './schema/built-in-media-types.ts'
65
66
  export * from './schema/built-in-member-types.ts'
67
+ export * from './schema/bundle-grant-delegate.ts'
66
68
  export * from './schema/bundle-grant-reach.ts'
67
69
  export * from './schema/bundle-grants.ts'
68
70
  export * from './schema/bundle-kind.ts'
@@ -85,6 +87,7 @@ export * from './schema/delivery-member-tokens.ts'
85
87
  export * from './schema/diagnostics.ts'
86
88
  export * from './schema/drop-assistant.ts'
87
89
  export * from './schema/elements.ts'
90
+ export * from './schema/extension-activity.ts'
88
91
  export * from './schema/extension-settings.ts'
89
92
  export * from './schema/form-library.ts'
90
93
  export * from './schema/form-library-types.ts'
@@ -14,10 +14,10 @@ export interface BundleGrant {
14
14
  /** What its `http.outbound` may reach (story 308); empty when it was granted none. */
15
15
  origins: string[]
16
16
  /**
17
- * Whom it acts for under `actAs`: `installer:<user key>`, `caller`, or
18
- * `user:<user key>`; null when it acts as itself.
17
+ * Who granted `user.delegate` (story 325): the user a job or an event acts
18
+ * for, when nobody is using it. Null for any other grant.
19
19
  */
20
- actAs: string | null
20
+ delegateKey: string | null
21
21
  grantedBy: string | null
22
22
  grantedAt: Date
23
23
  /**
@@ -54,7 +54,7 @@ export class BundleGrantRepository {
54
54
  version: row.version,
55
55
  permissions: permissionsOf(row.permissions),
56
56
  origins: row.origins ? permissionsOf(row.origins) : [],
57
- actAs: row.act_as ?? null,
57
+ delegateKey: row.delegate_key ?? null,
58
58
  grantedBy: row.granted_by ?? null,
59
59
  grantedAt: DbDate.fromDb(row.granted_at) ?? new Date(0),
60
60
  recorded: (DbDate.fromDb(row.granted_at)?.getTime() ?? 0) > 0,
@@ -76,7 +76,7 @@ export class BundleGrantRepository {
76
76
  version: grant.version,
77
77
  permissions: JSON.stringify(grant.permissions),
78
78
  origins: JSON.stringify(grant.origins),
79
- act_as: grant.actAs,
79
+ delegate_key: grant.delegateKey,
80
80
  granted_by: grant.grantedBy,
81
81
  granted_at: DbDate.toDb(new Date()),
82
82
  }
@@ -122,4 +122,9 @@ export class BundleGrantRepository {
122
122
  .execute()
123
123
  return before?.disabledAt != null
124
124
  }
125
+
126
+ /** Forgets a bundle's grant entirely, as removing it does (story 328). */
127
+ async forget(bundleId: string): Promise<void> {
128
+ await this.db.q.deleteFrom('bundle_grant').where('bundle_id', '=', bundleId).execute()
129
+ }
125
130
  }
@@ -48,4 +48,9 @@ export class ExtensionSettingRepository {
48
48
  })
49
49
  .execute()
50
50
  }
51
+
52
+ /** Forgets every setting an extension had, as removing it does (story 328). */
53
+ async forget(bundleId: string): Promise<void> {
54
+ await this.db.q.deleteFrom('extension_setting').where('bundle_id', '=', bundleId).execute()
55
+ }
51
56
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Migration 071 — who granted `user.delegate` (story 325), whom a job or an
3
+ * event acts for when nobody is using it. `actAs` is retired: a grant that
4
+ * chose the installer keeps that person here, and one that chose the caller or
5
+ * a named user has nothing to keep, since no version asking for `actAs` runs
6
+ * now. `act_as` stays, unread, so this release still upgrades node by node; a
7
+ * later release's contract drops it.
8
+ */
9
+ import type { Db } from '../database.ts'
10
+ import type { Migration } from '../migrations.ts'
11
+ import { schemaOps } from '../schema-ops.ts'
12
+ import { STATE_CONTENT_TYPE_SEO } from './content-type-seo.ts'
13
+
14
+ export const STATE_BUNDLE_GRANT_DELEGATE = '{9d4b27e6-0071-4c58-8a1f-3e6d5b2c7071}'
15
+
16
+ const INSTALLER = 'installer:'
17
+
18
+ export const bundleGrantDelegateMigration: Migration = {
19
+ from: STATE_CONTENT_TYPE_SEO,
20
+ to: STATE_BUNDLE_GRANT_DELEGATE,
21
+ name: 'AddBundleGrantDelegate',
22
+ kind: 'expand',
23
+ release: '0.61.0',
24
+ async up(db: Db) {
25
+ await schemaOps(db).addColumn('bundle_grant', 'delegate_key', db.dialect.types.varchar(36))
26
+ // One statement, reading nothing first, so `upgrade check` can plan it.
27
+ await db.q
28
+ .updateTable('bundle_grant')
29
+ .set((eb) => ({
30
+ delegate_key: eb.fn<string>('substr', ['act_as', eb.val(INSTALLER.length + 1)]),
31
+ }))
32
+ .where('act_as', 'like', `${INSTALLER}%`)
33
+ .execute()
34
+ },
35
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Migration 072 — what each extension did (story 327): one row per write,
3
+ * request out, rows written, refusal, call and screen, and one per minute for
4
+ * the reads of one kind it made for one person. No statement text, body or
5
+ * value is kept: the kind, the area, the verb, the key, a count, the outcome
6
+ * and the time taken.
7
+ */
8
+ import type { Db } from '../database.ts'
9
+ import type { Migration } from '../migrations.ts'
10
+ import { sql } from '../query.ts'
11
+ import { STATE_BUNDLE_GRANT_DELEGATE } from './bundle-grant-delegate.ts'
12
+
13
+ export const STATE_EXTENSION_ACTIVITY = '{a8e3c51d-0072-4b9e-9c04-6d2f7b1e8072}'
14
+
15
+ export const extensionActivityMigration: Migration = {
16
+ from: STATE_BUNDLE_GRANT_DELEGATE,
17
+ to: STATE_EXTENSION_ACTIVITY,
18
+ name: 'AddExtensionActivity',
19
+ kind: 'expand',
20
+ release: '0.61.0',
21
+ async up(db: Db) {
22
+ const t = db.dialect.types
23
+ await db.q.schema
24
+ .createTable('extension_activity')
25
+ .addColumn('id', sql.raw(t.identity))
26
+ .addColumn('extension_id', sql.raw(t.varchar(64)), (c) => c.notNull())
27
+ .addColumn('person_key', sql.raw(t.varchar(64)))
28
+ .addColumn('person_name', sql.raw(t.varchar(255)))
29
+ .addColumn('kind', sql.raw(t.varchar(16)), (c) => c.notNull())
30
+ .addColumn('area', sql.raw(t.varchar(255)))
31
+ .addColumn('verb', sql.raw(t.varchar(64)))
32
+ .addColumn('entity_key', sql.raw(t.varchar(255)))
33
+ .addColumn('count', sql.raw(t.integer), (c) => c.notNull())
34
+ .addColumn('outcome', sql.raw(t.varchar(16)), (c) => c.notNull())
35
+ .addColumn('ms', sql.raw(t.integer))
36
+ .addColumn('occurred_at', sql.raw(t.timestamp), (c) => c.notNull())
37
+ .execute()
38
+ await db.q.schema
39
+ .createIndex('extension_activity_by_extension')
40
+ .on('extension_activity')
41
+ .columns(['extension_id', 'occurred_at'])
42
+ .execute()
43
+ },
44
+ }
@@ -18,6 +18,7 @@ import { approvalsMigration } from './approvals.ts'
18
18
  import { assistantMigration } from './assistant.ts'
19
19
  import { auditLogMigration } from './audit-log.ts'
20
20
  import { bundleComponentsMigration } from './bundle-components.ts'
21
+ import { bundleGrantDelegateMigration } from './bundle-grant-delegate.ts'
21
22
  import { bundleGrantReachMigration } from './bundle-grant-reach.ts'
22
23
  import { bundleGrantsMigration } from './bundle-grants.ts'
23
24
  import { bundleKindMigration } from './bundle-kind.ts'
@@ -40,6 +41,7 @@ import { deliveryMemberTokensMigration } from './delivery-member-tokens.ts'
40
41
  import { diagnosticsMigration } from './diagnostics.ts'
41
42
  import { dropAssistantMigration } from './drop-assistant.ts'
42
43
  import { elementsMigration } from './elements.ts'
44
+ import { extensionActivityMigration } from './extension-activity.ts'
43
45
  import { extensionSettingsMigration } from './extension-settings.ts'
44
46
  import { formLibraryMigration } from './form-library.ts'
45
47
  import { formPermissionPrefixMigration } from './form-permission-prefix.ts'
@@ -155,4 +157,6 @@ export const cromboloPlan = new MigrationPlan([
155
157
  bundleKindMigration,
156
158
  trustedSignersMigration,
157
159
  contentTypeSeoMigration,
160
+ bundleGrantDelegateMigration,
161
+ extensionActivityMigration,
158
162
  ])
package/src/tables.gen.ts CHANGED
@@ -116,6 +116,7 @@ export interface CoreTables {
116
116
  bundle_grant: {
117
117
  act_as: string | null
118
118
  bundle_id: string
119
+ delegate_key: string | null
119
120
  disabled_at: Timestamp | null
120
121
  disabled_by: string | null
121
122
  granted_at: Timestamp
@@ -373,6 +374,20 @@ export interface CoreTables {
373
374
  node_id: number
374
375
  sort_order: number
375
376
  }
377
+ extension_activity: {
378
+ area: string | null
379
+ count: number
380
+ entity_key: string | null
381
+ extension_id: string
382
+ id: Generated<number>
383
+ kind: string
384
+ ms: number | null
385
+ occurred_at: Timestamp
386
+ outcome: string
387
+ person_key: string | null
388
+ person_name: string | null
389
+ verb: string | null
390
+ }
376
391
  extension_setting: {
377
392
  bundle_id: string
378
393
  setting_key: string