From 2db55bd636780c98c0672ba1ff5b4d931a9a6876 Mon Sep 17 00:00:00 2001 From: Juan Fernando Castro Date: Thu, 12 Nov 2026 20:06:29 -0500 Subject: [PATCH] perf(share): read share owners from the entry owner column and backfill missing ones (#4598) * perf(share): skip the legacy owner probe once a recorded share answers ownerHasShares ran its recorded-owner and legacy NULL-owner queries side by side, so the join to fsentries ran even when the first query already found a share. Run the legacy half only when the recorded half finds nothing; the answers stay the same. * perf(share): drop the NULL-owner fallbacks from owner and outbound reads ownerHasShares, listOutbound, countOutbound, the outbound apps summary and the team-row filter behind listByHolder/countByHolder each carried a second half for share rows written before entry_owner_user_id existed, matched by joining fsentries on a NULL owner. The column migration backfilled those rows from fsentries, so the joins only add work: each costs about min(owner's files, NULL-owner rows) per call. Every remaining read goes through entry_owner_user_id alone. Invite rows (no fsentry, no owner) are matched as before: they were never reachable through the joins. Self-contained so it can be reverted on its own. It assumes existing data has no share row that names an fsentry but has a NULL entry_owner_user_id; if any remain, they stop showing up in these reads. * fix(share): backfill the entry owner on share rows written without it The share reads now match on entry_owner_user_id alone. Add a migration for each engine that fills that column from fsentries on every row that names an entry but still has a NULL owner, so the backfill runs before the reads stop looking at NULL-owner rows and their answers don't depend on what existing data holds. Rows that name no entry (invites) keep a NULL owner, and a replay finds nothing to fill. * fix(share): record the entry owner when a claim names its entry applyPending can point a claimed invite at an entry, but left entry_owner_user_id NULL, so the row was missing from the owner's reads that now match on that column alone. Fill it from fsentries with the same subquery the upserts use. The share service claims without an entry today; the parameter stays for callers that pass one. * refactor(share): read the app from the data column directly Every caller of the app filter and the app expression passes the share row's own data column now, so the column argument goes. Also names the owner probe test after what it checks and puts back an unrelated line the earlier formatting pass had reflowed. * chore(share): drop the redundant MySQL and Postgres owner backfills MySQL and Postgres replay every migration file on boot, and mysql_mig_47 and postgres_mig_36 already end with the same owner backfill, so they re-run it on every boot. Only SQLite, which tracks a schema version and runs each file once, needs its own backfill migration (0103). * fix(share): list a team row for its members when no entry owner is recorded * refactor(share): claiming an invite leaves its entry and owner as written * test(db): run the share owner backfill against the full prior schema * fix(share): ship the owner backfill as its own MySQL and Postgres migration The backfill at the end of mysql_mig_47 and postgres_mig_36 replays on boot only when database.migrationPaths is set. A new file gives installs that apply migrations another way a step to run; a replay finds nothing to fill. --- .../database/SqliteDatabaseClient.test.ts | 56 +++++++- .../clients/database/SqliteDatabaseClient.ts | 1 + .../migrations/mysql/mysql_mig_57.sql | 25 ++++ .../migrations/postgres/postgres_mig_46.sql | 27 ++++ .../0103_share-entry-owner-backfill.sql | 27 ++++ .../services/share/ShareService.test.ts | 31 ----- src/backend/stores/share/ShareStore.js | 126 ++++-------------- src/backend/stores/share/ShareStore.test.js | 100 ++++++++++---- 8 files changed, 235 insertions(+), 158 deletions(-) create mode 100644 src/backend/clients/database/migrations/mysql/mysql_mig_57.sql create mode 100644 src/backend/clients/database/migrations/postgres/postgres_mig_46.sql create mode 100644 src/backend/clients/database/migrations/sqlite/0103_share-entry-owner-backfill.sql diff --git a/src/backend/clients/database/SqliteDatabaseClient.test.ts b/src/backend/clients/database/SqliteDatabaseClient.test.ts index df0e2d537..100ac38f0 100644 --- a/src/backend/clients/database/SqliteDatabaseClient.test.ts +++ b/src/backend/clients/database/SqliteDatabaseClient.test.ts @@ -27,7 +27,7 @@ import { DatabaseClientFactory } from './index.js'; import { SqliteDatabaseClient } from './SqliteDatabaseClient.js'; /** Highest schema version the migration table can reach. */ -const CURRENT_SCHEMA_VERSION = 98; +const CURRENT_SCHEMA_VERSION = 99; /** * These suites migrate real files on disk. Idle they finish in well under a @@ -705,6 +705,60 @@ describe('SqliteDatabaseClient — boot and migrations', { timeout: DISK_MIGRATI } }); + it('fills a share row missing its entry owner from 0103, invites left alone', async () => { + const dir = mkdtempSync(join(tmpdir(), 'puter-sqlite-share-owner-')); + const path = join(dir, 'puter.sqlite'); + try { + const before = new SqliteDatabaseClient( + sqliteConfig({ inMemory: false, path }), + ); + await before.onServerStart(); + const [user] = (await before.read( + 'SELECT MIN(`id`) AS id FROM `user`', + )) as { id: number }[]; + await before.write( + 'INSERT INTO `fsentries` (`uuid`, `name`, `user_id`, `modified`) ' + + 'VALUES (?, ?, ?, ?)', + ['22222222-2222-4222-8222-222222222222', 'owned.txt', user.id, 0], + ); + const [entry] = (await before.read( + 'SELECT `id` FROM `fsentries` WHERE `uuid` = ?', + ['22222222-2222-4222-8222-222222222222'], + )) as { id: number }[]; + await before.write( + 'INSERT INTO `share` (`uid`, `issuer_user_id`, ' + + '`recipient_email`, `fsentry_id`) VALUES (?, ?, ?, ?)', + ['share-no-owner', user.id, 'held@test.local', entry.id], + ); + await before.write( + 'INSERT INTO `share` (`uid`, `issuer_user_id`, ' + + '`recipient_email`) VALUES (?, ?, ?)', + ['share-invite', user.id, 'invite@test.local'], + ); + // The full schema as it stood before 0103, so only 0103 reruns. + await before.write('PRAGMA user_version = 98'); + before.onServerShutdown(); + + const after = new SqliteDatabaseClient( + sqliteConfig({ inMemory: false, path }), + ); + await after.onServerStart(); + await expect( + after.read( + 'SELECT `uid`, `entry_owner_user_id` FROM `share` ' + + 'WHERE `uid` IN (?, ?) ORDER BY `uid`', + ['share-invite', 'share-no-owner'], + ), + ).resolves.toEqual([ + { uid: 'share-invite', entry_owner_user_id: null }, + { uid: 'share-no-owner', entry_owner_user_id: user.id }, + ]); + after.onServerShutdown(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it('indexes notification.created_at for the retention sweep', async () => { const rows = await client.read('PRAGMA index_list(`notification`)'); expect(rows.map((r) => String(r.name))).toContain( diff --git a/src/backend/clients/database/SqliteDatabaseClient.ts b/src/backend/clients/database/SqliteDatabaseClient.ts index efdaf8a6e..24b5767ec 100644 --- a/src/backend/clients/database/SqliteDatabaseClient.ts +++ b/src/backend/clients/database/SqliteDatabaseClient.ts @@ -137,6 +137,7 @@ const AVAILABLE_MIGRATIONS: [number, string[]][] = [ [95, ['0100_notification-send-key.sql']], [96, ['0101_user-scoped-handlers.sql']], [97, ['0102_notification-scope-id-index.sql']], + [98, ['0103_share-entry-owner-backfill.sql']], ]; export class SqliteDatabaseClient extends AbstractDatabaseClient { diff --git a/src/backend/clients/database/migrations/mysql/mysql_mig_57.sql b/src/backend/clients/database/migrations/mysql/mysql_mig_57.sql new file mode 100644 index 000000000..521574e61 --- /dev/null +++ b/src/backend/clients/database/migrations/mysql/mysql_mig_57.sql @@ -0,0 +1,25 @@ +-- Copyright (C) 2024-present Puter Technologies Inc. +-- +-- This file is part of Puter. +-- +-- Puter is free software: you can redistribute it and/or modify +-- it under the terms of the GNU Affero General Public License as published +-- by the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU Affero General Public License for more details. +-- +-- You should have received a copy of the GNU Affero General Public License +-- along with this program. If not, see . + +-- Fills `share`.`entry_owner_user_id` on any row that names an entry but was +-- written without the owner. Mirrors SQLite migration 0103. No per-file +-- applied-state tracking; a replay finds nothing to fill. + +UPDATE `share` JOIN `fsentries` ON `fsentries`.`id` = `share`.`fsentry_id` +SET `share`.`entry_owner_user_id` = `fsentries`.`user_id` +WHERE `share`.`fsentry_id` IS NOT NULL + AND `share`.`entry_owner_user_id` IS NULL; diff --git a/src/backend/clients/database/migrations/postgres/postgres_mig_46.sql b/src/backend/clients/database/migrations/postgres/postgres_mig_46.sql new file mode 100644 index 000000000..bb3a2ec24 --- /dev/null +++ b/src/backend/clients/database/migrations/postgres/postgres_mig_46.sql @@ -0,0 +1,27 @@ +-- Copyright (C) 2024-present Puter Technologies Inc. +-- +-- This file is part of Puter. +-- +-- Puter is free software: you can redistribute it and/or modify +-- it under the terms of the GNU Affero General Public License as published +-- by the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU Affero General Public License for more details. +-- +-- You should have received a copy of the GNU Affero General Public License +-- along with this program. If not, see . + +-- Fills "share".entry_owner_user_id on any row that names an entry but was +-- written without the owner. Mirrors SQLite migration 0103. No per-file +-- applied-state tracking; a replay finds nothing to fill. + +UPDATE "share" +SET entry_owner_user_id = f.user_id +FROM fsentries f +WHERE f.id = "share".fsentry_id + AND "share".fsentry_id IS NOT NULL + AND "share".entry_owner_user_id IS NULL; diff --git a/src/backend/clients/database/migrations/sqlite/0103_share-entry-owner-backfill.sql b/src/backend/clients/database/migrations/sqlite/0103_share-entry-owner-backfill.sql new file mode 100644 index 000000000..4ae40d66c --- /dev/null +++ b/src/backend/clients/database/migrations/sqlite/0103_share-entry-owner-backfill.sql @@ -0,0 +1,27 @@ +-- Copyright (C) 2024-present Puter Technologies Inc. +-- +-- This file is part of Puter. +-- +-- Puter is free software: you can redistribute it and/or modify +-- it under the terms of the GNU Affero General Public License as published +-- by the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU Affero General Public License for more details. +-- +-- You should have received a copy of the GNU Affero General Public License +-- along with this program. If not, see . + +-- Fills `share`.`entry_owner_user_id` on any row that names an entry but was +-- written without the owner, so reads can rely on the column alone. Rows that +-- name no entry (invites) keep a NULL owner. A replay finds nothing to fill. + +UPDATE `share` +SET `entry_owner_user_id` = ( + SELECT `user_id` FROM `fsentries` WHERE `fsentries`.`id` = `share`.`fsentry_id` + ) +WHERE `fsentry_id` IS NOT NULL + AND `entry_owner_user_id` IS NULL; diff --git a/src/backend/services/share/ShareService.test.ts b/src/backend/services/share/ShareService.test.ts index caca55f10..5990bb946 100644 --- a/src/backend/services/share/ShareService.test.ts +++ b/src/backend/services/share/ShareService.test.ts @@ -1445,37 +1445,6 @@ describe('ShareService', () => { server.services.share.listSharedByMe(actor, opts), ); - it('still finds a row written before the owner was recorded', async () => { - const owner = await makeUser(); - const delegate = await makeUser(); - const third = await makeUser(); - const file = await makeFile(owner.user); - - await share(owner.actor, { - uid: file.uuid, - recipient: { email: delegate.email }, - mode: 'manage', - }); - await share(delegate.actor, { - uid: file.uuid, - recipient: { email: third.email }, - mode: 'read', - }); - - // What a writer that predates the column leaves behind. - await server.clients.db.write( - 'UPDATE `share` SET `entry_owner_user_id` = NULL', - ); - - const listed = await listSharedByMe(owner.actor, { - includeTotal: true, - }); - expect(listed.items.map((r) => r.holder?.username)).toContain( - third.user.username, - ); - expect(listed.total).toBeGreaterThanOrEqual(2); - }); - it("includes a delegate's share on an item the caller owns", async () => { const owner = await makeUser(); const delegate = await makeUser(); diff --git a/src/backend/stores/share/ShareStore.js b/src/backend/stores/share/ShareStore.js index ad0602a23..8730428d0 100644 --- a/src/backend/stores/share/ShareStore.js +++ b/src/backend/stores/share/ShareStore.js @@ -133,8 +133,7 @@ export class ShareStore extends PuterStore { * * Separate reads rather than one `OR`, which no index can serve. Each is a * range scan: the issued half on `idx_share_issuer`, the delegated half on - * `idx_share_entry_owner`, and a third covering rows written before that - * column existed, which is empty once none remain. Unclaimed invites are + * `idx_share_entry_owner`, each bounded by its limit. Unclaimed invites are * included (an invite is something the user sent); the legacy invite rows * that name no node are not. * @@ -147,11 +146,9 @@ export class ShareStore extends PuterStore { async listOutbound(userId, { limit, cursor, appUid } = {}) { const size = this.#pageSize(limit); const afterId = this.#afterId(cursor); - const own = this.#appFilter(appUid, '`data`'); + const own = this.#appFilter(appUid); - const joined = this.#appFilter(appUid, '`share`.`data`'); - - const [issued, delegated, unrecorded] = await Promise.all([ + const [issued, delegated] = await Promise.all([ this.clients.db.read( 'SELECT * FROM `share` WHERE `issuer_user_id` = ? AND ' + '`fsentry_id` IS NOT NULL AND `id` > ?' + @@ -166,23 +163,12 @@ export class ShareStore extends PuterStore { ' ORDER BY `id` LIMIT ?', [userId, userId, afterId, ...own.params, size + 1], ), - // Rows left by a writer predating the column; indexed on the NULL. - this.clients.db.read( - 'SELECT `share`.* FROM `share` JOIN `fsentries` ON ' + - '`fsentries`.`id` = `share`.`fsentry_id` WHERE ' + - '`share`.`entry_owner_user_id` IS NULL AND ' + - '`fsentries`.`user_id` = ? AND `share`.`issuer_user_id` <> ? ' + - 'AND `share`.`id` > ?' + - joined.sql + - ' ORDER BY `share`.`id` LIMIT ?', - [userId, userId, afterId, ...joined.params, size + 1], - ), ]); // The halves are disjoint and each ordered by id, so merging them and // cutting at `size` is the true next page: whatever either half lost to // its own limit sorts after the cut and returns on the following one. - const merged = [...issued, ...delegated, ...unrecorded].sort( + const merged = [...issued, ...delegated].sort( (a, b) => Number(a.id) - Number(b.id), ); const page = keysetPage(merged, size, this.config.jwt_secret_v2); @@ -200,9 +186,8 @@ export class ShareStore extends PuterStore { * @param {{ appUid?: string | null }} [opts] */ async countOutbound(userId, { appUid } = {}) { - const own = this.#appFilter(appUid, '`data`'); - const joined = this.#appFilter(appUid, '`share`.`data`'); - const [issued, delegated, unrecorded] = await Promise.all([ + const own = this.#appFilter(appUid); + const [issued, delegated] = await Promise.all([ this.clients.db.read( 'SELECT COUNT(*) AS `count` FROM `share` WHERE ' + '`issuer_user_id` = ? AND `fsentry_id` IS NOT NULL' + @@ -215,21 +200,8 @@ export class ShareStore extends PuterStore { own.sql, [userId, userId, ...own.params], ), - // As `listOutbound`: rows written before the column existed. - this.clients.db.read( - 'SELECT COUNT(*) AS `count` FROM `share` JOIN `fsentries` ON ' + - '`fsentries`.`id` = `share`.`fsentry_id` WHERE ' + - '`share`.`entry_owner_user_id` IS NULL AND ' + - '`fsentries`.`user_id` = ? AND `share`.`issuer_user_id` <> ?' + - joined.sql, - [userId, userId, ...joined.params], - ), ]); - return ( - Number(issued[0]?.count ?? 0) + - Number(delegated[0]?.count ?? 0) + - Number(unrecorded[0]?.count ?? 0) - ); + return Number(issued[0]?.count ?? 0) + Number(delegated[0]?.count ?? 0); } /** @@ -263,8 +235,6 @@ export class ShareStore extends PuterStore { (after === null ? '' : ' WHERE `app_uid` > ?') + ' GROUP BY `app_uid` ORDER BY `app_uid` LIMIT ?', [ - userId, - userId, userId, userId, userId, @@ -292,7 +262,7 @@ export class ShareStore extends PuterStore { 'SELECT COUNT(*) AS `count` FROM (SELECT DISTINCT `app_uid` FROM (' + this.#outboundAppsSql() + ') AS `outbound`) AS `apps`', - [userId, userId, userId, userId, userId], + [userId, userId, userId], ); return Number(rows[0]?.count ?? 0); } @@ -415,28 +385,18 @@ export class ShareStore extends PuterStore { /** * Whether any share row sits on one of `userId`'s entries. A write to an * owner with none has no audience to look for, and nearly every owner has - * none. Rows from before `entry_owner_user_id` existed are matched through - * their entry, as `listOutbound` does. + * none. * * @param {number} userId * @returns {Promise} */ async ownerHasShares(userId) { - const [recorded, unrecorded] = await Promise.all([ - this.clients.db.read( - 'SELECT 1 AS `found` FROM `share` WHERE ' + - '`entry_owner_user_id` = ? LIMIT 1', - [userId], - ), - this.clients.db.read( - 'SELECT 1 AS `found` FROM `share` JOIN `fsentries` ON ' + - '`fsentries`.`id` = `share`.`fsentry_id` WHERE ' + - '`share`.`entry_owner_user_id` IS NULL AND ' + - '`fsentries`.`user_id` = ? LIMIT 1', - [userId], - ), - ]); - return recorded.length > 0 || unrecorded.length > 0; + const rows = await this.clients.db.read( + 'SELECT 1 AS `found` FROM `share` WHERE ' + + '`entry_owner_user_id` = ? LIMIT 1', + [userId], + ); + return rows.length > 0; } /** @@ -511,8 +471,8 @@ export class ShareStore extends PuterStore { /** * The holder's own rows, plus their teams' rows on items that aren't * theirs: what they shared with their own team, or a teammate shared of - * something they own, was not shared with them. Rows predating - * `entry_owner_user_id` are matched through their entry. + * something they own, was not shared with them. A row with no owner + * recorded is listed: the grant exists whoever owns the entry. */ #holderClause(holderUserId, groups) { if (groups.length === 0) { @@ -526,17 +486,8 @@ export class ShareStore extends PuterStore { '(`holder_user_id` = ? OR (`holder_group_id` IN (' + groups.map(() => '?').join(', ') + ') AND `issuer_user_id` <> ? AND ' + - '(`entry_owner_user_id` <> ? OR (`entry_owner_user_id` IS NULL ' + - 'AND NOT EXISTS (SELECT 1 FROM `fsentries` WHERE ' + - '`fsentries`.`id` = `share`.`fsentry_id` AND ' + - '`fsentries`.`user_id` = ?)))))', - holderParams: [ - holderUserId, - ...groups, - holderUserId, - holderUserId, - holderUserId, - ], + '(`entry_owner_user_id` IS NULL OR `entry_owner_user_id` <> ?)))', + holderParams: [holderUserId, ...groups, holderUserId, holderUserId], }; } @@ -966,24 +917,17 @@ export class ShareStore extends PuterStore { * @param {object} input * @param {string} input.uid * @param {number} input.holderUserId - * @param {number | null} [input.fsentryId] * @param {string | null} [input.mode] */ - async applyPending({ uid, holderUserId, fsentryId = null, mode = null }) { + async applyPending({ uid, holderUserId, mode = null }) { if (!uid || !holderUserId) { throw new Error('applyPending: uid and holderUserId are required'); } const result = await this.clients.db.write( 'UPDATE `share` SET `holder_user_id` = ?, `applied_at` = CURRENT_TIMESTAMP' + - (fsentryId === null ? '' : ', `fsentry_id` = ?') + (mode === null ? '' : ', `mode` = ?') + ' WHERE `uid` = ? AND `holder_user_id` IS NULL', - [ - holderUserId, - ...(fsentryId === null ? [] : [fsentryId]), - ...(mode === null ? [] : [mode]), - uid, - ], + [holderUserId, ...(mode === null ? [] : [mode]), uid], ); if ((result?.affectedRows ?? result?.changes ?? 0) === 0) return null; // Only the uid is known here; the caller holds the replica's copy. @@ -1413,13 +1357,13 @@ export class ShareStore extends PuterStore { * whatever it was handed and legacy rows carry plain strings — extracting * from one of those aborts the whole query, so there the read is guarded. */ - #issuedByAppExpr(dataColumn) { + #issuedByAppExpr() { const extracts = ['issuedByApp', 'issuerAppUid'].map((key) => - this.clients.db.jsonTextExtract(dataColumn, [key]), + this.clients.db.jsonTextExtract('`data`', [key]), ); const coalesced = `COALESCE(${extracts.join(', ')})`; return this.clients.db.case({ - sqlite: `CASE WHEN json_valid(${dataColumn}) THEN ${coalesced} END`, + sqlite: `CASE WHEN json_valid(\`data\`) THEN ${coalesced} END`, otherwise: coalesced, }); } @@ -1429,37 +1373,25 @@ export class ShareStore extends PuterStore { * app, `null` the rows no app issued. * * @param {string | null | undefined} appUid - * @param {string} dataColumn */ - #appFilter(appUid, dataColumn) { + #appFilter(appUid) { if (appUid === undefined) return { sql: '', params: [] }; - const expr = this.#issuedByAppExpr(dataColumn); + const expr = this.#issuedByAppExpr(); if (appUid === null) return { sql: ` AND ${expr} IS NULL`, params: [] }; return { sql: ` AND ${expr} = ?`, params: [appUid] }; } /** * Both outbound halves projected onto their issuing app. Takes the same - * five bound user ids as `listOutbound`, in that order. + * three bound user ids as `listOutbound`, in that order. */ #outboundAppsSql() { - const own = this.clients.db.nullCoalesce( - this.#issuedByAppExpr('`data`'), - "''", - ); - const joined = this.clients.db.nullCoalesce( - this.#issuedByAppExpr('`share`.`data`'), - "''", - ); + const own = this.clients.db.nullCoalesce(this.#issuedByAppExpr(), "''"); return ( `SELECT ${own} AS \`app_uid\` FROM \`share\` WHERE ` + '`issuer_user_id` = ? AND `fsentry_id` IS NOT NULL UNION ALL ' + `SELECT ${own} AS \`app_uid\` FROM \`share\` WHERE ` + - '`entry_owner_user_id` = ? AND `issuer_user_id` <> ? UNION ALL ' + - `SELECT ${joined} AS \`app_uid\` FROM \`share\` JOIN \`fsentries\` ` + - 'ON `fsentries`.`id` = `share`.`fsentry_id` WHERE ' + - '`share`.`entry_owner_user_id` IS NULL AND ' + - '`fsentries`.`user_id` = ? AND `share`.`issuer_user_id` <> ?' + '`entry_owner_user_id` = ? AND `issuer_user_id` <> ?' ); } diff --git a/src/backend/stores/share/ShareStore.test.js b/src/backend/stores/share/ShareStore.test.js index 6ee6eaa6f..de01dfb3a 100644 --- a/src/backend/stores/share/ShareStore.test.js +++ b/src/backend/stores/share/ShareStore.test.js @@ -171,10 +171,19 @@ describe('ShareStore', () => { holder = await makeUser(); }); - it('says whether an owner has anything shared, legacy rows included', async () => { + it('says an owner with nothing shared has no shares', async () => { const owner = await makeUser(); + await makeEntry(owner); + // An invite row that names no node is not a share of an entry. + await store.create({ + issuerUserId: owner.id, + recipientEmail: `${owner.username}-invite@test.local`, + }); await expect(store.ownerHasShares(owner.id)).resolves.toBe(false); + }); + it('answers with one indexed read', async () => { + const owner = await makeUser(); const entry = await makeEntry(owner); await store.upsertActive({ issuerUserId: owner.id, @@ -182,24 +191,24 @@ describe('ShareStore', () => { fsentryId: entry.id, mode: 'read', }); - await expect(store.ownerHasShares(owner.id)).resolves.toBe(true); - // A row written before the owner column existed. - const legacyOwner = await makeUser(); - const legacy = await makeEntry(legacyOwner); - await store.upsertActive({ - issuerUserId: legacyOwner.id, - holderUserId: holder.id, - fsentryId: legacy.id, - mode: 'read', - }); - await server.clients.db.write( - 'UPDATE `share` SET `entry_owner_user_id` = NULL WHERE `fsentry_id` = ?', - [legacy.id], - ); - await expect(store.ownerHasShares(legacyOwner.id)).resolves.toBe( - true, - ); + const read = vi.spyOn(server.clients.db, 'read'); + const pread = vi.spyOn(server.clients.db, 'pread'); + try { + await expect(store.ownerHasShares(owner.id)).resolves.toBe( + true, + ); + const sql = [...read.mock.calls, ...pread.mock.calls].map( + ([query]) => String(query), + ); + expect(sql).toHaveLength(1); + expect(sql.some((q) => q.includes('JOIN `fsentries`'))).toBe( + false, + ); + } finally { + read.mockRestore(); + pread.mockRestore(); + } }); it('finds a subtree share even when the descendant has no path yet', async () => { @@ -859,12 +868,6 @@ describe('ShareStore', () => { await groupRow(member.id, await makeEntry(member)); // A teammate's share of the member's item. await groupRow(mate.id, await makeEntry(member)); - // As that, from before `entry_owner_user_id` was recorded. - const legacy = await groupRow(mate.id, await makeEntry(member)); - await server.clients.db.write( - 'UPDATE `share` SET `entry_owner_user_id` = NULL WHERE `uid` = ?', - [legacy.uid], - ); const theirs = await groupRow(mate.id, await makeEntry(mate)); const direct = await store.upsertActive({ issuerUserId: mate.id, @@ -886,6 +889,36 @@ describe('ShareStore', () => { expect(await store.countByHolder(mate.id, opts)).toBe(1); }); + it('lists a team row whose entry owner was never recorded', async () => { + const member = await makeUser(); + const mate = await makeUser(); + const groupUid = uuidv4(); + await server.clients.db.write( + 'INSERT INTO `group` (`uid`, `owner_user_id`, `kind`, ' + + '`name`, `extra`, `metadata`) VALUES (?, ?, ?, ?, ?, ?)', + [groupUid, member.id, 'team', 'No owner', '{}', '{}'], + ); + const [{ id: groupId }] = await server.clients.db.read( + 'SELECT `id` FROM `group` WHERE `uid` = ?', + [groupUid], + ); + const row = await store.upsertActiveGroup({ + issuerUserId: mate.id, + holderGroupId: Number(groupId), + fsentryId: (await makeEntry(mate)).id, + mode: 'read', + }); + await server.clients.db.write( + 'UPDATE `share` SET `entry_owner_user_id` = NULL WHERE `uid` = ?', + [row.uid], + ); + + const opts = { groupIds: [Number(groupId)] }; + const page = await store.listByHolder(member.id, opts); + expect(page.items.map((r) => r.uid)).toEqual([row.uid]); + expect(await store.countByHolder(member.id, opts)).toBe(1); + }); + it('lists what a user issued alongside what was issued on their node', async () => { const owner = await makeUser(); const delegate = await makeUser(); @@ -1142,22 +1175,25 @@ describe('ShareStore', () => { it('claims a pending invite without dropping the row', async () => { const entry = await makeEntry(issuer); - const pending = await store.create({ + const { row: pending } = await store.upsertPending({ issuerUserId: issuer.id, recipientEmail: `pending-${uuidv4()}@test.local`, - data: {}, + fsentryId: entry.id, + mode: 'write', }); const applied = await store.applyPending({ uid: pending.uid, holderUserId: holder.id, - fsentryId: entry.id, mode: 'read', }); expect(applied.holder_user_id).toBe(holder.id); expect(applied.mode).toBe('read'); expect(applied.applied_at).toBeTruthy(); + // The entry and its owner are the ones the invite was written with. + expect(Number(applied.fsentry_id)).toBe(entry.id); + expect(Number(applied.entry_owner_user_id)).toBe(issuer.id); // Second claim finds nothing left to claim. expect( await store.applyPending({ @@ -1354,7 +1390,14 @@ describe('ShareStore', () => { await server.clients.db.write( 'INSERT INTO `group` (`uid`, `owner_user_id`, `kind`, ' + '`name`, `extra`, `metadata`) VALUES (?, ?, ?, ?, ?, ?)', - [groupUid, issuer.id, 'team', 'Lagging replica', '{}', '{}'], + [ + groupUid, + issuer.id, + 'team', + 'Lagging replica', + '{}', + '{}', + ], ); const [team] = await server.clients.db.read( 'SELECT id FROM `group` WHERE uid = ?', @@ -1459,7 +1502,6 @@ describe('ShareStore', () => { const applied = await store.applyPending({ uid: claimable.uid, holderUserId: holder.id, - fsentryId: (await makeEntry(issuer)).id, mode: 'read', }); expect(applied.holder_user_id).toBe(holder.id);