2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Module to manage "active" Grist documents, i.e. those loaded in-memory, with
|
|
|
|
* clients connected to them. It handles the incoming user actions, and outgoing
|
|
|
|
* change events.
|
|
|
|
*/
|
|
|
|
|
2022-12-05 16:37:48 +00:00
|
|
|
import {ACLRuleCollection} from 'app/common/ACLRuleCollection';
|
2022-06-17 18:49:18 +00:00
|
|
|
import {
|
|
|
|
getEnvContent,
|
|
|
|
LocalActionBundle,
|
|
|
|
SandboxActionBundle,
|
|
|
|
SandboxRequest,
|
|
|
|
UserActionBundle
|
|
|
|
} from 'app/common/ActionBundle';
|
2021-12-07 11:21:16 +00:00
|
|
|
import {ActionGroup, MinimalActionGroup} from 'app/common/ActionGroup';
|
|
|
|
import {ActionSummary} from "app/common/ActionSummary";
|
2021-07-01 15:15:43 +00:00
|
|
|
import {
|
2022-12-05 16:37:48 +00:00
|
|
|
AclResources,
|
2022-07-18 11:57:56 +00:00
|
|
|
AclTableDescription,
|
2022-11-15 14:37:48 +00:00
|
|
|
ApplyUAExtendedOptions,
|
2021-07-01 15:15:43 +00:00
|
|
|
ApplyUAOptions,
|
|
|
|
ApplyUAResult,
|
|
|
|
DataSourceTransformed,
|
|
|
|
ForkResult,
|
2021-09-15 06:12:34 +00:00
|
|
|
ImportOptions,
|
2021-07-01 15:15:43 +00:00
|
|
|
ImportResult,
|
(core) Show example values in formula autocomplete
Summary:
This diff adds a preview of the value of certain autocomplete suggestions, especially of the form `$foo.bar` or `user.email`. The main initial motivation was to show the difference between `$Ref` and `$Ref.DisplayCol`, but the feature is more general.
The client now sends the row ID of the row being edited (along with the table and column IDs which were already sent) to the server to fetch autocomplete suggestions. The returned suggestions are now tuples `(suggestion, example_value)` where `example_value` is a string or null. The example value is simply obtained by evaluating (in a controlled way) the suggestion in the context of the given record and the current user. The string representation is similar to the standard `repr` but dates and datetimes are formatted, and the whole thing is truncated for efficiency.
The example values are shown in the autocomplete popup separated from the actual suggestion by a number of spaces calculated to:
1. Clearly separate the suggestion from the values
2. Left-align the example values in most cases
3. Avoid having so much space such that connecting suggestions and values becomes visually difficult.
The tokenization of the row is then tweaked to show the example in light grey to deemphasise it.
Main discussion where the above was decided: https://grist.slack.com/archives/CDHABLZJT/p1661795588100009
The diff also includes various other small improvements and fixes:
- The autocomplete popup is much wider to make room for long suggestions, particularly lookups, as pointed out in https://phab.getgrist.com/D3580#inline-41007. The wide popup is the reason a fancy solution was needed to position the example values. I didn't see a way to dynamically resize the popup based on suggestions, and it didn't seem like a good idea to try.
- The `grist` and `python` labels previously shown on the right are removed. They were not helpful (https://grist.slack.com/archives/CDHABLZJT/p1659697086155179) and would get in the way of the example values.
- Fixed a bug in our custom tokenization that caused function arguments to be weirdly truncated in the middle: https://grist.slack.com/archives/CDHABLZJT/p1661956353699169?thread_ts=1661953258.342739&cid=CDHABLZJT and https://grist.slack.com/archives/C069RUP71/p1659696778991339
- Hide suggestions involving helper columns like `$gristHelper_Display` or `Table.lookupRecords(gristHelper_Display=` (https://grist.slack.com/archives/CDHABLZJT/p1661953258342739). The former has been around for a while and seems to be a mistake. The fix is simply to use `is_visible_column` instead of `is_user_column`. Since the latter is not used anywhere else, and using it in the first place seems like a mistake more than anything else, I've also removed the function to prevent similar mistakes in the future.
- Don't suggest private columns as lookup arguments: https://grist.slack.com/archives/CDHABLZJT/p1662133416652499?thread_ts=1661795588.100009&cid=CDHABLZJT
- Only fetch fresh suggestions specifically after typing `lookupRecords(` or `lookupOne(` rather than just `(`, as this would needlessly hide function suggestions which could still be useful to see the arguments. However this only makes a difference when there are still multiple matching suggestions, otherwise Ace hides them anyway.
Test Plan: Extended and updated several Python and browser tests.
Reviewers: paulfitz
Reviewed By: paulfitz
Differential Revision: https://phab.getgrist.com/D3611
2022-09-28 14:47:55 +00:00
|
|
|
ISuggestionWithValue,
|
2021-10-08 06:32:59 +00:00
|
|
|
MergeOptions,
|
2021-10-08 14:56:33 +00:00
|
|
|
PermissionDataWithExtraUsers,
|
2021-08-10 18:21:03 +00:00
|
|
|
QueryResult,
|
2021-10-08 06:32:59 +00:00
|
|
|
ServerQuery,
|
2022-12-21 16:40:00 +00:00
|
|
|
TableFetchResult,
|
2021-10-08 06:32:59 +00:00
|
|
|
TransformRule
|
2021-07-01 15:15:43 +00:00
|
|
|
} from 'app/common/ActiveDocAPI';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {ApiError} from 'app/common/ApiError';
|
2023-03-17 03:25:44 +00:00
|
|
|
import {mapGetOrSet, MapWithTTL} from 'app/common/AsyncCreate';
|
2022-12-21 16:40:00 +00:00
|
|
|
import {AttachmentColumns, gatherAttachmentIds, getAttachmentColumns} from 'app/common/AttachmentColumns';
|
2023-07-18 07:24:10 +00:00
|
|
|
import {WebhookMessageType} from 'app/common/CommTypes';
|
2021-07-01 15:15:43 +00:00
|
|
|
import {
|
2022-12-21 16:40:00 +00:00
|
|
|
BulkAddRecord,
|
2022-04-12 14:33:48 +00:00
|
|
|
BulkRemoveRecord,
|
2022-04-07 12:34:50 +00:00
|
|
|
BulkUpdateRecord,
|
2021-07-01 15:15:43 +00:00
|
|
|
CellValue,
|
|
|
|
DocAction,
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
getTableId,
|
2022-12-21 16:40:00 +00:00
|
|
|
isSchemaAction,
|
2021-07-01 15:15:43 +00:00
|
|
|
TableDataAction,
|
|
|
|
toTableDataAction,
|
|
|
|
UserAction
|
|
|
|
} from 'app/common/DocActions';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {DocData} from 'app/common/DocData';
|
2022-06-17 18:49:18 +00:00
|
|
|
import {getDataLimitRatio, getDataLimitStatus, getSeverity, LimitExceededError} from 'app/common/DocLimits';
|
2020-10-30 16:53:23 +00:00
|
|
|
import {DocSnapshots} from 'app/common/DocSnapshot';
|
2021-09-15 23:35:21 +00:00
|
|
|
import {DocumentSettings} from 'app/common/DocumentSettings';
|
2022-05-03 05:20:31 +00:00
|
|
|
import {
|
|
|
|
APPROACHING_LIMIT_RATIO,
|
|
|
|
DataLimitStatus,
|
2022-05-16 17:41:12 +00:00
|
|
|
DocumentUsage,
|
|
|
|
DocUsageSummary,
|
|
|
|
FilteredDocUsageSummary,
|
|
|
|
getUsageRatio,
|
2022-08-03 07:18:21 +00:00
|
|
|
RowCounts,
|
2022-05-03 05:20:31 +00:00
|
|
|
} from 'app/common/DocUsage';
|
2021-10-08 14:56:33 +00:00
|
|
|
import {normalizeEmail} from 'app/common/emails';
|
2022-06-06 16:21:26 +00:00
|
|
|
import {Product} from 'app/common/Features';
|
2021-03-10 14:08:46 +00:00
|
|
|
import {FormulaProperties, getFormulaProperties} from 'app/common/GranularAccessClause';
|
2023-04-06 15:10:29 +00:00
|
|
|
import {isHiddenCol} from 'app/common/gristTypes';
|
|
|
|
import {commonUrls, parseUrlId} from 'app/common/gristUrls';
|
2023-09-13 05:58:05 +00:00
|
|
|
import {byteString, countIf, retryOnce, safeJsonParse, timeoutReached} from 'app/common/gutil';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {InactivityTimer} from 'app/common/InactivityTimer';
|
2022-08-25 19:20:32 +00:00
|
|
|
import {Interval} from 'app/common/Interval';
|
2022-07-19 15:39:49 +00:00
|
|
|
import * as roles from 'app/common/roles';
|
2021-10-01 13:45:27 +00:00
|
|
|
import {schema, SCHEMA_VERSION} from 'app/common/schema';
|
2023-08-28 09:16:17 +00:00
|
|
|
import {MetaRowRecord, SingleCell} from 'app/common/TableData';
|
2023-06-06 17:08:50 +00:00
|
|
|
import {TelemetryEvent, TelemetryMetadataByLevel} from 'app/common/Telemetry';
|
2021-09-30 08:19:22 +00:00
|
|
|
import {FetchUrlOptions, UploadResult} from 'app/common/uploads';
|
2023-04-06 15:10:29 +00:00
|
|
|
import {Document as APIDocument, DocReplacementOptions, DocState, DocStateComparison} from 'app/common/UserAPI';
|
2022-02-04 11:13:03 +00:00
|
|
|
import {convertFromColumn} from 'app/common/ValueConverter';
|
2023-06-07 18:19:10 +00:00
|
|
|
import {guessColInfo} from 'app/common/ValueGuesser';
|
2021-12-16 13:45:05 +00:00
|
|
|
import {parseUserAction} from 'app/common/ValueParser';
|
2023-02-20 02:51:40 +00:00
|
|
|
import {Document} from 'app/gen-server/entity/Document';
|
2024-01-12 17:35:24 +00:00
|
|
|
import {Share} from 'app/gen-server/entity/Share';
|
(core) Improve API Console and link from Document Settings.
Summary:
Changes to building and serving:
- Remove unpkg dependencies, add npm module for swagger-ui-dist instead.
- Move apiconsole JS logic into core/app/client/apiconsole.ts, and use TypeScript.
- Add symlinks to swagger in static/ and core/static/.
- Refactor loadScript, and add loadCssFile; use these to load swagger-ui resources.
Changes to console itself:
- Support docId, workspaceId, orgId URL parameters. When present, the matching
value in dropdowns is moved to the front and marked as "(Current)".
- Fix the ordering of example values, particularly for workspaces.
- Remove unwanted example values.
- Hide confusing "Authorize" button.
- Hide API keys, and rely consistently on cookies for executing API calls.
Integration into Grist:
- Added a button to Document Settings, just under document ID in "API".
- The button opens a separate page, passing in org, workspace, and doc info for the current doc.
Test Plan: Only tested manually, no automated tests yet.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D4173
2024-01-27 04:21:34 +00:00
|
|
|
import {RecordWithStringId} from 'app/plugin/DocApiTypes';
|
2023-07-12 13:57:02 +00:00
|
|
|
import {ParseFileResult, ParseOptions} from 'app/plugin/FileParserAPI';
|
2023-08-28 09:16:17 +00:00
|
|
|
import {AccessTokenOptions, AccessTokenResult, GristDocAPI, UIRowId} from 'app/plugin/GristAPI';
|
2020-12-15 04:19:38 +00:00
|
|
|
import {compileAclFormula} from 'app/server/lib/ACLFormula';
|
2023-07-05 15:36:45 +00:00
|
|
|
import {AssistanceSchemaPromptV1Context} from 'app/server/lib/Assistance';
|
2023-07-24 18:56:38 +00:00
|
|
|
import {AssistanceContext} from 'app/common/AssistancePrompts';
|
2023-10-12 17:32:22 +00:00
|
|
|
import {Authorizer, RequestWithLogin} from 'app/server/lib/Authorizer';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {checksumFile} from 'app/server/lib/checksumFile';
|
|
|
|
import {Client} from 'app/server/lib/Client';
|
2024-01-12 17:35:24 +00:00
|
|
|
import {getMetaTables} from 'app/server/lib/DocApi';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {DEFAULT_CACHE_TTL, DocManager} from 'app/server/lib/DocManager';
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
import {ICreateActiveDocOptions} from 'app/server/lib/ICreate';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {makeForkIds} from 'app/server/lib/idUtils';
|
2021-10-01 13:45:27 +00:00
|
|
|
import {GRIST_DOC_SQL, GRIST_DOC_WITH_TABLE1_SQL} from 'app/server/lib/initialDocSql';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {ISandbox} from 'app/server/lib/ISandbox';
|
2022-07-04 14:14:55 +00:00
|
|
|
import log from 'app/server/lib/log';
|
2021-10-25 13:29:06 +00:00
|
|
|
import {LogMethods} from "app/server/lib/LogMethods";
|
2023-05-23 19:03:50 +00:00
|
|
|
import {NullSandbox, UnavailableSandboxMethodError} from 'app/server/lib/NullSandbox';
|
2022-06-17 18:49:18 +00:00
|
|
|
import {DocRequests} from 'app/server/lib/Requests';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {shortDesc} from 'app/server/lib/shortDesc';
|
2021-10-01 13:45:27 +00:00
|
|
|
import {TableMetadataLoader} from 'app/server/lib/TableMetadataLoader';
|
2021-12-07 11:21:16 +00:00
|
|
|
import {DocTriggers} from "app/server/lib/Triggers";
|
2020-07-21 13:20:51 +00:00
|
|
|
import {fetchURL, FileUploadInfo, globalUploadSet, UploadInfo} from 'app/server/lib/uploads';
|
2022-07-04 14:14:55 +00:00
|
|
|
import assert from 'assert';
|
2021-12-07 11:21:16 +00:00
|
|
|
import {Mutex} from 'async-mutex';
|
|
|
|
import * as bluebird from 'bluebird';
|
|
|
|
import {EventEmitter} from 'events';
|
|
|
|
import {IMessage, MsgType} from 'grain-rpc';
|
2022-07-04 14:14:55 +00:00
|
|
|
import imageSize from 'image-size';
|
2021-12-07 11:21:16 +00:00
|
|
|
import * as moment from 'moment-timezone';
|
|
|
|
import fetch from 'node-fetch';
|
2022-06-14 14:12:46 +00:00
|
|
|
import {createClient, RedisClient} from 'redis';
|
2022-07-04 14:14:55 +00:00
|
|
|
import tmp from 'tmp';
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2020-09-18 23:29:11 +00:00
|
|
|
import {ActionHistory} from './ActionHistory';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {ActionHistoryImpl} from './ActionHistoryImpl';
|
2023-07-12 13:57:02 +00:00
|
|
|
import {ActiveDocImport, FileImportOptions} from './ActiveDocImport';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {DocClients} from './DocClients';
|
|
|
|
import {DocPluginManager} from './DocPluginManager';
|
2021-07-01 15:15:43 +00:00
|
|
|
import {
|
|
|
|
DocSession,
|
2022-07-19 15:39:49 +00:00
|
|
|
getDocSessionAccess,
|
2023-04-06 15:10:29 +00:00
|
|
|
getDocSessionAltSessionId,
|
(core) notify home db of shares when copying/forking/uploading docs
Summary:
The first time a worker opens a document, it will now check if it has any shares the home db needs to be aware of. If so, they will be added. This is important for documents uploaded/copied/forked/replaced, so that their shares work out of the box.
In future, may want some UI to give user control of whether shares are activated after upload/copy/fork/replace.
It seems tricky currently to know if a document is being opened for the first time. As a proxy, I check whether usage information has been calculated and saved to the db, since I can determine that without adding another db query. It is safe to synchronize shares more than necessary.
This leaves two gaps:
* If a document is created/uploaded/copied/forked/replaced and no attempt is made to access it prior to using a share, then that share won't actually be available. Not a problem currently I think, since how would a user have determined the share key. But in future it would be good to also do a sync after creation/upload/copy/fork/replacement/...
* On document replacement, usage info is reset but not absolutely immediately. So in principle shares could fail to be created on first load of the replacement. Usage info reset could be tweaked to give a guarantee here, but also fixing the first point would resolve this second point too.
Test Plan: copy test added
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D4165
2024-01-12 22:05:13 +00:00
|
|
|
getDocSessionUsage,
|
2021-07-01 15:15:43 +00:00
|
|
|
getDocSessionUser,
|
|
|
|
getDocSessionUserId,
|
|
|
|
makeExceptionalDocSession,
|
|
|
|
OptDocSession
|
|
|
|
} from './DocSession';
|
2022-11-15 14:37:48 +00:00
|
|
|
import {createAttachmentsIndex, DocStorage, REMOVE_UNUSED_ATTACHMENTS_DELAY} from './DocStorage';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {expandQuery} from './ExpandedQuery';
|
2021-03-01 16:51:30 +00:00
|
|
|
import {GranularAccess, GranularAccessForBundle} from './GranularAccess';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {OnDemandActions} from './OnDemandActions';
|
2023-09-13 05:58:05 +00:00
|
|
|
import {getLogMetaFromDocSession, getPubSubPrefix, getTelemetryMetaFromDocSession} from './serverUtils';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {findOrAddAllEnvelope, Sharing} from './Sharing';
|
2021-07-01 15:15:43 +00:00
|
|
|
import cloneDeep = require('lodash/cloneDeep');
|
|
|
|
import flatten = require('lodash/flatten');
|
2023-05-18 22:35:39 +00:00
|
|
|
import merge = require('lodash/merge');
|
2022-11-15 14:37:48 +00:00
|
|
|
import pick = require('lodash/pick');
|
2021-07-01 15:15:43 +00:00
|
|
|
import remove = require('lodash/remove');
|
2022-04-14 12:19:36 +00:00
|
|
|
import sum = require('lodash/sum');
|
2021-10-04 16:14:14 +00:00
|
|
|
import without = require('lodash/without');
|
2021-12-07 11:21:16 +00:00
|
|
|
import zipObject = require('lodash/zipObject');
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
bluebird.promisifyAll(tmp);
|
|
|
|
|
|
|
|
const MAX_RECENT_ACTIONS = 100;
|
|
|
|
|
|
|
|
const DEFAULT_TIMEZONE = (process.versions as any).electron ? moment.tz.guess() : "UTC";
|
2022-08-24 19:24:50 +00:00
|
|
|
const DEFAULT_LOCALE = process.env.GRIST_DEFAULT_LOCALE || "en-US";
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
// Number of seconds an ActiveDoc is retained without any clients.
|
|
|
|
// In dev environment, it is convenient to keep this low for quick tests.
|
|
|
|
// In production, it is reasonable to stretch it out a bit.
|
|
|
|
const ACTIVEDOC_TIMEOUT = (process.env.NODE_ENV === 'production') ? 30 : 5;
|
|
|
|
|
|
|
|
// We'll wait this long between re-measuring sandbox memory.
|
|
|
|
const MEMORY_MEASUREMENT_INTERVAL_MS = 60 * 1000;
|
|
|
|
|
2022-04-25 20:31:23 +00:00
|
|
|
// Apply the UpdateCurrentTime user action every hour
|
2022-08-25 19:20:32 +00:00
|
|
|
const UPDATE_CURRENT_TIME_DELAY = {delayMs: 60 * 60 * 1000, varianceMs: 30 * 1000};
|
2022-04-25 20:31:23 +00:00
|
|
|
|
2022-06-06 16:21:26 +00:00
|
|
|
// Measure and broadcast data size every 5 minutes
|
2022-08-25 19:20:32 +00:00
|
|
|
const UPDATE_DATA_SIZE_DELAY = {delayMs: 5 * 60 * 1000, varianceMs: 30 * 1000};
|
2022-06-06 16:21:26 +00:00
|
|
|
|
2023-04-06 15:10:29 +00:00
|
|
|
// Log document metrics every hour
|
|
|
|
const LOG_DOCUMENT_METRICS_DELAY = {delayMs: 60 * 60 * 1000, varianceMs: 30 * 1000};
|
|
|
|
|
2023-09-13 05:58:05 +00:00
|
|
|
// For items of work that need to happen at shutdown, timeout before aborting the wait for them.
|
|
|
|
const SHUTDOWN_ITEM_TIMEOUT_MS = 5000;
|
|
|
|
|
|
|
|
// We keep a doc open while a user action is pending, but not longer than this. If it's pending
|
|
|
|
// this long, the ACTIVEDOC_TIMEOUT will still kick in afterwards, and in the absence of other
|
|
|
|
// activity, the doc would still get shut down, with the action's effect lost. This is to prevent
|
|
|
|
// indefinitely running processes in case of an infinite loop in a formula.
|
|
|
|
const KEEP_DOC_OPEN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// A hook for dependency injection.
|
2023-05-23 19:17:28 +00:00
|
|
|
export const Deps = {
|
|
|
|
ACTIVEDOC_TIMEOUT,
|
|
|
|
ACTIVEDOC_TIMEOUT_ACTION: 'shutdown' as 'shutdown'|'ignore',
|
2023-09-13 05:58:05 +00:00
|
|
|
|
|
|
|
UPDATE_CURRENT_TIME_DELAY,
|
|
|
|
SHUTDOWN_ITEM_TIMEOUT_MS,
|
|
|
|
KEEP_DOC_OPEN_TIMEOUT_MS,
|
2023-05-23 19:17:28 +00:00
|
|
|
};
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-06-06 16:21:26 +00:00
|
|
|
interface UpdateUsageOptions {
|
|
|
|
// Whether usage should be synced to the home database. Defaults to true.
|
|
|
|
syncUsageToDatabase?: boolean;
|
|
|
|
// Whether usage should be broadcast to all doc clients. Defaults to true.
|
|
|
|
broadcastUsageToClients?: boolean;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Represents an active document with the given name. The document isn't actually open until
|
2021-10-01 13:45:27 +00:00
|
|
|
* either .loadDoc() or .createEmptyDoc() is called.
|
2020-07-21 13:20:51 +00:00
|
|
|
* @param {String} docName - The document's filename, without the '.grist' extension.
|
|
|
|
*/
|
2023-07-05 15:36:45 +00:00
|
|
|
export class ActiveDoc extends EventEmitter {
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Decorator for ActiveDoc methods that prevents shutdown while the method is running, i.e.
|
2023-09-13 05:58:05 +00:00
|
|
|
* until the returned promise is resolved, or KEEP_DOC_OPEN_TIMEOUT_MS passes.
|
2020-07-21 13:20:51 +00:00
|
|
|
*/
|
|
|
|
public static keepDocOpen(target: ActiveDoc, propertyKey: string, descriptor: PropertyDescriptor) {
|
|
|
|
const origFunc = descriptor.value;
|
|
|
|
descriptor.value = function(this: ActiveDoc) {
|
2023-09-13 05:58:05 +00:00
|
|
|
const result = origFunc.apply(this, arguments);
|
|
|
|
this._inactivityTimer.disableUntilFinish(timeoutReached(Deps.KEEP_DOC_OPEN_TIMEOUT_MS, result))
|
|
|
|
.catch(() => {});
|
|
|
|
return result;
|
2020-07-21 13:20:51 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
public readonly docStorage: DocStorage;
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
public readonly docPluginManager: DocPluginManager|null;
|
2020-07-21 13:20:51 +00:00
|
|
|
public readonly docClients: DocClients; // Only exposed for Sharing.ts
|
|
|
|
public docData: DocData|null = null;
|
2023-11-14 13:46:33 +00:00
|
|
|
// Used by DocApi to only allow one webhook-related endpoint to run at a time.
|
|
|
|
public readonly triggersLock: Mutex = new Mutex();
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
protected _actionHistory: ActionHistory;
|
|
|
|
protected _docManager: DocManager;
|
|
|
|
protected _docName: string;
|
|
|
|
protected _sharing: Sharing;
|
2020-12-07 21:15:58 +00:00
|
|
|
// This lock is used to avoid reading sandbox state while it is being modified but before
|
|
|
|
// the result has been confirmed to pass granular access rules (which may depend on the
|
|
|
|
// result).
|
|
|
|
protected _modificationLock: Mutex = new Mutex();
|
|
|
|
|
2022-08-25 19:20:32 +00:00
|
|
|
private _log = new LogMethods('ActiveDoc ', (s: OptDocSession | null) => this.getLogMeta(s));
|
2021-10-15 13:12:13 +00:00
|
|
|
private _triggers: DocTriggers;
|
2022-06-17 18:49:18 +00:00
|
|
|
private _requests: DocRequests;
|
2023-05-23 19:03:50 +00:00
|
|
|
private _dataEngine: Promise<ISandbox>|null = null;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _activeDocImport: ActiveDocImport;
|
|
|
|
private _onDemandActions: OnDemandActions;
|
2020-09-11 20:27:09 +00:00
|
|
|
private _granularAccess: GranularAccess;
|
2021-10-01 13:45:27 +00:00
|
|
|
private _tableMetadataLoader: TableMetadataLoader;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _muted: boolean = false; // If set, changes to this document should not propagate
|
|
|
|
// to outside world
|
2020-10-30 16:53:23 +00:00
|
|
|
private _migrating: number = 0; // If positive, a migration is in progress
|
2022-03-24 20:27:34 +00:00
|
|
|
private _initializationPromise: Promise<void>|null = null;
|
2020-07-21 13:20:51 +00:00
|
|
|
// If set, wait on this to be sure the ActiveDoc is fully
|
|
|
|
// initialized. True on success.
|
|
|
|
private _fullyLoaded: boolean = false; // Becomes true once all columns are loaded/computed.
|
2022-03-30 11:45:37 +00:00
|
|
|
private _lastMemoryMeasurement: number = 0; // Timestamp when memory was last measured.
|
2020-07-21 13:20:51 +00:00
|
|
|
private _fetchCache = new MapWithTTL<string, Promise<TableDataAction>>(DEFAULT_CACHE_TTL);
|
2023-04-06 15:10:29 +00:00
|
|
|
private _doc: Document|undefined;
|
2022-05-16 17:41:12 +00:00
|
|
|
private _docUsage: DocumentUsage|null = null;
|
2022-06-06 16:21:26 +00:00
|
|
|
private _product?: Product;
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
private _gracePeriodStart: Date|null = null;
|
2023-04-11 05:56:26 +00:00
|
|
|
private _isSnapshot: boolean;
|
|
|
|
private _isForkOrSnapshot: boolean;
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
private _onlyAllowMetaDataActionsOnDb: boolean = false;
|
2022-12-21 16:40:00 +00:00
|
|
|
// Cache of which columns are attachment columns.
|
|
|
|
private _attachmentColumns?: AttachmentColumns;
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-06-14 14:12:46 +00:00
|
|
|
// Client watching for 'product changed' event published by Billing to update usage
|
|
|
|
private _redisSubscriber?: RedisClient;
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Timer for shutting down the ActiveDoc a bit after all clients are gone.
|
2023-04-12 16:18:48 +00:00
|
|
|
private _inactivityTimer = new InactivityTimer(() => {
|
|
|
|
this._log.debug(null, 'inactivity timeout');
|
2023-05-23 19:17:28 +00:00
|
|
|
return this._onInactive();
|
2023-04-12 16:18:48 +00:00
|
|
|
}, Deps.ACTIVEDOC_TIMEOUT * 1000);
|
2020-12-14 17:42:09 +00:00
|
|
|
private _recoveryMode: boolean = false;
|
2021-09-15 23:35:21 +00:00
|
|
|
private _shuttingDown: boolean = false;
|
2023-03-15 08:52:17 +00:00
|
|
|
private _afterShutdownCallback?: () => Promise<void>;
|
2023-03-17 03:25:44 +00:00
|
|
|
private _doShutdown?: Promise<void>;
|
2023-04-11 05:56:26 +00:00
|
|
|
private _intervals: Interval[] = [];
|
2022-04-22 18:07:14 +00:00
|
|
|
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
constructor(docManager: DocManager, docName: string, private _options?: ICreateActiveDocOptions) {
|
2020-07-21 13:20:51 +00:00
|
|
|
super();
|
2022-05-16 17:41:12 +00:00
|
|
|
const {forkId, snapshotId} = parseUrlId(docName);
|
2023-04-11 05:56:26 +00:00
|
|
|
this._isSnapshot = Boolean(snapshotId);
|
2022-05-16 17:41:12 +00:00
|
|
|
this._isForkOrSnapshot = Boolean(forkId || snapshotId);
|
2023-04-11 05:56:26 +00:00
|
|
|
if (!this._isSnapshot) {
|
|
|
|
/**
|
|
|
|
* In cases where large numbers of documents are restarted simultaneously
|
|
|
|
* (like during deployments), there's a tendency for scheduled intervals to
|
|
|
|
* execute at roughly the same moment in time, which causes spikes in load.
|
|
|
|
*
|
|
|
|
* To mitigate this, we use randomized intervals that re-compute their delay
|
|
|
|
* in-between calls, with a variance of 30 seconds.
|
|
|
|
*/
|
|
|
|
this._intervals.push(
|
|
|
|
// Cleanup expired attachments every hour (also happens when shutting down).
|
|
|
|
new Interval(
|
|
|
|
() => this.removeUnusedAttachments(true),
|
|
|
|
REMOVE_UNUSED_ATTACHMENTS_DELAY,
|
|
|
|
{onError: (e) => this._log.error(null, 'failed to remove expired attachments', e)},
|
|
|
|
),
|
|
|
|
// Update the time in formulas every hour.
|
|
|
|
new Interval(
|
|
|
|
() => this._applyUserActions(makeExceptionalDocSession('system'), [['UpdateCurrentTime']]),
|
2023-09-13 05:58:05 +00:00
|
|
|
Deps.UPDATE_CURRENT_TIME_DELAY,
|
2023-04-11 05:56:26 +00:00
|
|
|
{onError: (e) => this._log.error(null, 'failed to update current time', e)},
|
|
|
|
),
|
|
|
|
// Measure and broadcast data size every 5 minutes.
|
|
|
|
new Interval(
|
|
|
|
() => this._checkDataSizeLimitRatio(makeExceptionalDocSession('system')),
|
|
|
|
UPDATE_DATA_SIZE_DELAY,
|
|
|
|
{onError: (e) => this._log.error(null, 'failed to update data size', e)},
|
|
|
|
),
|
|
|
|
// Log document metrics every hour.
|
|
|
|
new Interval(
|
|
|
|
() => this._logDocMetrics(makeExceptionalDocSession('system'), 'interval'),
|
|
|
|
LOG_DOCUMENT_METRICS_DELAY,
|
|
|
|
{onError: (e) => this._log.error(null, 'failed to log document metrics', e)},
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
2021-09-15 23:35:21 +00:00
|
|
|
if (_options?.safeMode) { this._recoveryMode = true; }
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
if (_options?.doc) {
|
2023-04-06 15:10:29 +00:00
|
|
|
this._doc = _options.doc;
|
|
|
|
const {gracePeriodStart, workspace, usage} = this._doc;
|
2022-06-14 14:12:46 +00:00
|
|
|
const billingAccount = workspace.org.billingAccount;
|
|
|
|
this._product = billingAccount?.product;
|
2022-05-16 17:41:12 +00:00
|
|
|
this._gracePeriodStart = gracePeriodStart;
|
|
|
|
|
2022-06-14 14:12:46 +00:00
|
|
|
if (process.env.REDIS_URL && billingAccount) {
|
2023-04-12 16:18:48 +00:00
|
|
|
const prefix = getPubSubPrefix();
|
|
|
|
const channel = `${prefix}-billingAccount-${billingAccount.id}-product-changed`;
|
2022-06-14 14:12:46 +00:00
|
|
|
this._redisSubscriber = createClient(process.env.REDIS_URL);
|
|
|
|
this._redisSubscriber.subscribe(channel);
|
|
|
|
this._redisSubscriber.on("message", async () => {
|
|
|
|
// A product change has just happened in Billing.
|
|
|
|
// Reload the doc (causing connected clients to reload) to ensure everyone sees the effect of the change.
|
2023-04-12 16:18:48 +00:00
|
|
|
this._log.debug(null, 'reload after product change');
|
2022-06-14 14:12:46 +00:00
|
|
|
await this.reloadDoc();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
if (!this._isForkOrSnapshot) {
|
|
|
|
/* Note: We don't currently persist usage for forks or snapshots anywhere, so
|
|
|
|
* we need to hold off on setting _docUsage here. Normally, usage is set shortly
|
|
|
|
* after initialization finishes, after data/attachments size has finished
|
|
|
|
* calculating. However, this leaves a narrow window where forks can circumvent
|
|
|
|
* delete-only restrictions and replace the trunk document (even when the trunk
|
|
|
|
* is delete-only). This isn't very concerning today as the window is typically
|
|
|
|
* too narrow to easily exploit, and there are other ways to work around limits,
|
|
|
|
* like resetting gracePeriodStart by momentarily lowering usage. Regardless, it
|
|
|
|
* would be good to fix this eventually (perhaps around the same time we close
|
|
|
|
* up the gracePeriodStart loophole).
|
|
|
|
*
|
|
|
|
* TODO: Revisit this later and patch up the loophole. */
|
|
|
|
this._docUsage = usage;
|
|
|
|
}
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
this._docManager = docManager;
|
|
|
|
this._docName = docName;
|
|
|
|
this.docStorage = new DocStorage(docManager.storageManager, docName);
|
|
|
|
this.docClients = new DocClients(this);
|
2021-10-15 13:12:13 +00:00
|
|
|
this._triggers = new DocTriggers(this);
|
2022-06-17 18:49:18 +00:00
|
|
|
this._requests = new DocRequests(this);
|
2020-07-21 13:20:51 +00:00
|
|
|
this._actionHistory = new ActionHistoryImpl(this.docStorage);
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
this.docPluginManager = docManager.pluginManager ?
|
|
|
|
new DocPluginManager(docManager.pluginManager.getPlugins(),
|
|
|
|
docManager.pluginManager.appRoot!, this, this._docManager.gristServer) : null;
|
2021-10-01 13:45:27 +00:00
|
|
|
this._tableMetadataLoader = new TableMetadataLoader({
|
|
|
|
decodeBuffer: this.docStorage.decodeMarshalledData.bind(this.docStorage),
|
|
|
|
fetchTable: this.docStorage.fetchTable.bind(this.docStorage),
|
|
|
|
loadMetaTables: this._rawPyCall.bind(this, 'load_meta_tables'),
|
|
|
|
loadTable: this._rawPyCall.bind(this, 'load_table'),
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2021-11-05 14:36:33 +00:00
|
|
|
// Our DataEngine is a separate sandboxed process (one sandbox per open document,
|
|
|
|
// corresponding to one process for pynbox, more for gvisor).
|
|
|
|
// The data engine runs user-defined python code including formula calculations.
|
|
|
|
// It maintains all document data and metadata, and applies translates higher-level UserActions
|
|
|
|
// into lower-level DocActions.
|
|
|
|
|
|
|
|
// Creation of the data engine needs to be deferred since we need to look at the document to
|
|
|
|
// see what kind of engine it needs. This doesn't delay loading the document, but could delay
|
|
|
|
// first calculation and modification.
|
|
|
|
// TODO: consider caching engine requirement for doc in home db - or running python2
|
|
|
|
// in gvisor (but would still need to look at doc to know what process to start in sandbox)
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
this._activeDocImport = new ActiveDocImport(this);
|
|
|
|
|
|
|
|
// Schedule shutdown immediately. If a client connects soon (normal case), it will get
|
|
|
|
// unscheduled. If not (e.g. abandoned import, network problems after creating a doc), then
|
|
|
|
// the ActiveDoc will get cleaned up.
|
|
|
|
this._inactivityTimer.enable();
|
|
|
|
}
|
|
|
|
|
|
|
|
public get docName(): string { return this._docName; }
|
|
|
|
|
2020-12-14 17:42:09 +00:00
|
|
|
public get recoveryMode(): boolean { return this._recoveryMode; }
|
|
|
|
|
2021-09-15 23:35:21 +00:00
|
|
|
public get isShuttingDown(): boolean { return this._shuttingDown; }
|
|
|
|
|
2023-03-01 20:43:22 +00:00
|
|
|
public get triggers(): DocTriggers { return this._triggers; }
|
2022-04-21 17:57:33 +00:00
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
public get rowLimitRatio(): number {
|
|
|
|
return getUsageRatio(
|
2022-08-03 07:18:21 +00:00
|
|
|
this._docUsage?.rowCount?.total,
|
2022-06-06 16:21:26 +00:00
|
|
|
this._product?.features.baseMaxRowsPerDocument
|
2022-05-16 17:41:12 +00:00
|
|
|
);
|
2022-03-30 11:45:37 +00:00
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
public get dataSizeLimitRatio(): number {
|
|
|
|
return getUsageRatio(
|
|
|
|
this._docUsage?.dataSizeBytes,
|
2022-06-06 16:21:26 +00:00
|
|
|
this._product?.features.baseMaxDataSizePerDocument
|
2022-05-16 17:41:12 +00:00
|
|
|
);
|
2022-03-30 11:45:37 +00:00
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
public get dataLimitRatio(): number {
|
2022-06-06 16:21:26 +00:00
|
|
|
return getDataLimitRatio(this._docUsage, this._product?.features);
|
2022-03-30 11:45:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public get dataLimitStatus(): DataLimitStatus {
|
2022-05-16 17:41:12 +00:00
|
|
|
return getDataLimitStatus({
|
|
|
|
docUsage: this._docUsage,
|
2022-06-06 16:21:26 +00:00
|
|
|
productFeatures: this._product?.features,
|
2022-05-16 17:41:12 +00:00
|
|
|
gracePeriodStart: this._gracePeriodStart,
|
|
|
|
});
|
2022-03-30 11:45:37 +00:00
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
public getDocUsageSummary(): DocUsageSummary {
|
2022-05-03 05:20:31 +00:00
|
|
|
return {
|
|
|
|
dataLimitStatus: this.dataLimitStatus,
|
2022-05-16 17:41:12 +00:00
|
|
|
rowCount: this._docUsage?.rowCount ?? 'pending',
|
|
|
|
dataSizeBytes: this._docUsage?.dataSizeBytes ?? 'pending',
|
|
|
|
attachmentsSizeBytes: this._docUsage?.attachmentsSizeBytes ?? 'pending',
|
2022-05-03 05:20:31 +00:00
|
|
|
};
|
2022-03-14 18:16:30 +00:00
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
public async getFilteredDocUsageSummary(
|
|
|
|
docSession: OptDocSession
|
|
|
|
): Promise<FilteredDocUsageSummary> {
|
|
|
|
return this._granularAccess.filterDocUsageSummary(docSession, this.getDocUsageSummary());
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
}
|
|
|
|
|
2021-01-15 21:56:58 +00:00
|
|
|
public async getUserOverride(docSession: OptDocSession) {
|
|
|
|
return this._granularAccess.getUserOverride(docSession);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Constructs metadata for logging, given a Client or an OptDocSession.
|
2021-10-25 13:29:06 +00:00
|
|
|
public getLogMeta(docSession: OptDocSession|null, docMethod?: string): log.ILogMeta {
|
2020-07-21 13:20:51 +00:00
|
|
|
return {
|
2021-10-25 13:29:06 +00:00
|
|
|
...(docSession ? getLogMetaFromDocSession(docSession) : {}),
|
2020-07-21 13:20:51 +00:00
|
|
|
docId: this._docName,
|
|
|
|
...(docMethod ? {docMethod} : {}),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
public setMuted() {
|
|
|
|
this._muted = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public get muted() {
|
|
|
|
return this._muted;
|
|
|
|
}
|
|
|
|
|
2020-10-30 16:53:23 +00:00
|
|
|
public isMigrating() {
|
|
|
|
return this._migrating;
|
|
|
|
}
|
|
|
|
|
2020-09-18 23:29:11 +00:00
|
|
|
// Note that this method is only used in tests, and should be avoided in production (see note
|
|
|
|
// in ActionHistory about getRecentActions).
|
2020-07-21 13:20:51 +00:00
|
|
|
public getRecentActionsDirect(maxActions?: number): Promise<LocalActionBundle[]> {
|
|
|
|
return this._actionHistory.getRecentActions(maxActions);
|
|
|
|
}
|
|
|
|
|
2020-09-11 20:27:09 +00:00
|
|
|
public async getRecentStates(docSession: OptDocSession, maxStates?: number): Promise<DocState[]> {
|
|
|
|
// Doc states currently don't include user content, so it seems ok to let all
|
|
|
|
// viewers have access to them.
|
2020-07-21 13:20:51 +00:00
|
|
|
return this._actionHistory.getRecentStates(maxStates);
|
|
|
|
}
|
|
|
|
|
2020-09-18 18:43:01 +00:00
|
|
|
/**
|
|
|
|
* Access specific actions identified by actionNum.
|
|
|
|
* TODO: for memory reasons on large docs, would be best not to hold many actions
|
|
|
|
* in memory at a time, so should e.g. fetch them one at a time.
|
|
|
|
*/
|
|
|
|
public getActions(actionNums: number[]): Promise<Array<LocalActionBundle|undefined>> {
|
|
|
|
return this._actionHistory.getActions(actionNums);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Get the most recent actions from the history. Results are ordered by
|
|
|
|
* earliest actions first, later actions later. If `summarize` is set,
|
|
|
|
* action summaries are computed and included.
|
|
|
|
*/
|
2020-09-02 18:17:17 +00:00
|
|
|
public async getRecentActions(docSession: OptDocSession, summarize: boolean): Promise<ActionGroup[]> {
|
2020-09-18 23:29:11 +00:00
|
|
|
const groups = await this._actionHistory.getRecentActionGroups(MAX_RECENT_ACTIONS,
|
2021-09-29 13:57:55 +00:00
|
|
|
{clientId: docSession.client?.clientId, summarize});
|
2020-12-11 19:22:35 +00:00
|
|
|
const permittedGroups: ActionGroup[] = [];
|
|
|
|
// Process groups serially since the work is synchronous except for some
|
|
|
|
// possible db accesses that will be serialized in any case.
|
|
|
|
for (const group of groups) {
|
|
|
|
if (await this._granularAccess.allowActionGroup(docSession, group)) {
|
|
|
|
permittedGroups.push(group);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return permittedGroups;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2021-09-29 13:57:55 +00:00
|
|
|
public async getRecentMinimalActions(docSession: OptDocSession): Promise<MinimalActionGroup[]> {
|
|
|
|
return this._actionHistory.getRecentMinimalActionGroups(
|
|
|
|
MAX_RECENT_ACTIONS, docSession.client?.clientId);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/** expose action history for tests */
|
|
|
|
public getActionHistory(): ActionHistory {
|
|
|
|
return this._actionHistory;
|
|
|
|
}
|
|
|
|
|
2021-11-10 19:14:23 +00:00
|
|
|
public handleTriggers(localActionBundle: LocalActionBundle): Promise<ActionSummary> {
|
|
|
|
return this._triggers.handle(localActionBundle);
|
2021-10-15 13:12:13 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Adds a client of this doc to the list of connected clients.
|
|
|
|
* @param client: The client object maintaining the websocket connection.
|
|
|
|
* @param authorizer: The authorizer for the client/doc combination.
|
|
|
|
* @returns docSession
|
|
|
|
*/
|
|
|
|
public addClient(client: Client, authorizer: Authorizer): DocSession {
|
|
|
|
const docSession: DocSession = this.docClients.addClient(client, authorizer);
|
|
|
|
|
|
|
|
// If we had a shutdown scheduled, unschedule it.
|
|
|
|
if (this._inactivityTimer.isEnabled()) {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "will stay open");
|
2020-07-21 13:20:51 +00:00
|
|
|
this._inactivityTimer.disable();
|
|
|
|
}
|
|
|
|
return docSession;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2021-11-16 21:10:57 +00:00
|
|
|
* Shut down the ActiveDoc, and remove it from the DocManager. An optional
|
|
|
|
* afterShutdown operation can be provided, which will be run once the ActiveDoc
|
|
|
|
* is completely shut down but before it is removed from the DocManager, ensuring
|
|
|
|
* that the operation will not overlap with a new ActiveDoc starting up for the
|
|
|
|
* same document.
|
2020-07-21 13:20:51 +00:00
|
|
|
*/
|
2021-11-16 21:10:57 +00:00
|
|
|
public async shutdown(options: {
|
|
|
|
afterShutdown?: () => Promise<void>
|
|
|
|
} = {}): Promise<void> {
|
2023-03-15 08:52:17 +00:00
|
|
|
if (options.afterShutdown) {
|
|
|
|
this._afterShutdownCallback = options.afterShutdown;
|
|
|
|
}
|
2023-03-17 03:25:44 +00:00
|
|
|
this._doShutdown ||= this._doShutdownImpl();
|
|
|
|
await this._doShutdown;
|
2023-03-15 08:52:17 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
2021-10-01 13:45:27 +00:00
|
|
|
* Create a new blank document (no "Table1") using the data engine. This is used only
|
|
|
|
* to generate the SQL saved to initialDocSql.ts
|
2021-11-05 14:36:33 +00:00
|
|
|
*
|
|
|
|
* It does not set documentSettings.engine. When a document is created during normal
|
|
|
|
* operation, documentSettings.engine gets set after the SQL is used to seed it, in
|
|
|
|
* _createDocFile()
|
|
|
|
*
|
2020-07-21 13:20:51 +00:00
|
|
|
*/
|
|
|
|
@ActiveDoc.keepDocOpen
|
2021-10-01 13:45:27 +00:00
|
|
|
public async createEmptyDocWithDataEngine(docSession: OptDocSession): Promise<ActiveDoc> {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "createEmptyDocWithDataEngine");
|
2020-12-21 14:46:50 +00:00
|
|
|
await this._docManager.storageManager.prepareToCreateDoc(this.docName);
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.docStorage.createFile();
|
2020-12-07 21:15:58 +00:00
|
|
|
await this._rawPyCall('load_empty');
|
2020-07-21 13:20:51 +00:00
|
|
|
// This init action is special. It creates schema tables, and is used to init the DB, but does
|
|
|
|
// not go through other steps of a regular action (no ActionHistory or broadcasting).
|
2022-04-22 21:53:39 +00:00
|
|
|
const initBundle = await this._rawPyCall('apply_user_actions', [["InitNewDoc"]]);
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.docStorage.execTransaction(() =>
|
|
|
|
this.docStorage.applyStoredActions(getEnvContent(initBundle.stored)));
|
2022-04-19 15:19:35 +00:00
|
|
|
// DocStorage can't create this index in the initial schema
|
|
|
|
// because the table _grist_Attachments doesn't exist at that point - it's created by InitNewDoc.
|
|
|
|
await createAttachmentsIndex(this.docStorage);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
await this._initDoc(docSession);
|
2021-10-01 13:45:27 +00:00
|
|
|
await this._tableMetadataLoader.clean();
|
|
|
|
// Makes sure docPluginManager is ready in case new doc is used to import new data
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
await this.docPluginManager?.ready;
|
2021-10-01 13:45:27 +00:00
|
|
|
this._fullyLoaded = true;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new blank document (no "Table1"), used as a stub when importing.
|
|
|
|
*/
|
|
|
|
@ActiveDoc.keepDocOpen
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
public async createEmptyDoc(docSession: OptDocSession,
|
|
|
|
options?: { useExisting?: boolean }): Promise<ActiveDoc> {
|
|
|
|
await this.loadDoc(docSession, {forceNew: true,
|
|
|
|
skipInitialTable: true,
|
|
|
|
...options});
|
2020-07-21 13:20:51 +00:00
|
|
|
// Makes sure docPluginManager is ready in case new doc is used to import new data
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
await this.docPluginManager?.ready;
|
2020-07-21 13:20:51 +00:00
|
|
|
this._fullyLoaded = true;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Loads an existing document from storage, fetching all data from the database via DocStorage and
|
|
|
|
* loading it into the DataEngine. User tables are not immediately loaded (see use of
|
|
|
|
* this.waitForInitialization throughout this class to wait for that).
|
|
|
|
* @returns {Promise} Promise for this ActiveDoc itself.
|
|
|
|
*/
|
|
|
|
@ActiveDoc.keepDocOpen
|
2021-10-01 13:45:27 +00:00
|
|
|
public async loadDoc(docSession: OptDocSession, options?: {
|
|
|
|
forceNew?: boolean, // If set, document will be created.
|
|
|
|
skipInitialTable?: boolean, // If set, and document is new, "Table1" will not be added.
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
useExisting?: boolean, // If set, document can be created as an overlay on
|
|
|
|
// an existing sqlite file.
|
2021-10-01 13:45:27 +00:00
|
|
|
}): Promise<ActiveDoc> {
|
2020-07-21 13:20:51 +00:00
|
|
|
const startTime = Date.now();
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "loadDoc");
|
2020-07-21 13:20:51 +00:00
|
|
|
try {
|
2021-10-01 13:45:27 +00:00
|
|
|
const isNew: boolean = options?.forceNew || await this._docManager.storageManager.prepareLocalDoc(this.docName);
|
2020-07-21 13:20:51 +00:00
|
|
|
if (isNew) {
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
await this._createDocFile(docSession, {
|
|
|
|
skipInitialTable: options?.skipInitialTable,
|
|
|
|
useExisting: options?.useExisting,
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
} else {
|
2020-10-30 16:53:23 +00:00
|
|
|
await this.docStorage.openFile({
|
|
|
|
beforeMigration: async (currentVersion, newVersion) => {
|
|
|
|
return this._beforeMigration(docSession, 'storage', currentVersion, newVersion);
|
|
|
|
},
|
|
|
|
afterMigration: async (newVersion, success) => {
|
|
|
|
return this._afterMigration(docSession, 'storage', newVersion, success);
|
|
|
|
},
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
(core) Log statistics about table sizes
Summary:
Record numbers of rows, columns, cells, and bytes of marshalled data for most calls to table_data_from_db
Export new function get_table_stats in the sandbox, which gives the raw numbers and totals.
Get and log these stats in ActiveDoc right after loading tables, before Calculate, so they are logged even in case of errors.
Tweak logging about number of tables, especially number of on-demand tables, to not only show in debug logging.
Test Plan: Updated doc regression tests, that shows what the data looks like nicely.
Reviewers: dsagal, paulfitz
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D3081
2021-10-21 13:03:37 +00:00
|
|
|
const [tableNames, onDemandNames] = await this._loadOpenDoc(docSession);
|
2021-10-01 13:45:27 +00:00
|
|
|
const desiredTableNames = tableNames.filter(name => name.startsWith('_grist_'));
|
|
|
|
this._startLoadingTables(docSession, desiredTableNames);
|
|
|
|
const pendingTableNames = tableNames.filter(name => !name.startsWith('_grist_'));
|
|
|
|
await this._initDoc(docSession);
|
2022-05-18 16:05:37 +00:00
|
|
|
this._initializationPromise = this._finishInitialization(docSession, pendingTableNames,
|
|
|
|
onDemandNames, startTime).catch(async (err) => {
|
|
|
|
await this.docClients.broadcastDocMessage(null, 'docError', {
|
|
|
|
when: 'initialization',
|
|
|
|
message: String(err),
|
|
|
|
});
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
} catch (err) {
|
2022-07-14 22:19:18 +00:00
|
|
|
const level = err.status === 404 ? "warn" : "error";
|
|
|
|
this._log.log(level, docSession, "Failed to load document", err);
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.shutdown();
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Replace this document with another, in-place so its id and other metadata does not change.
|
|
|
|
* This operation will leave the ActiveDoc it is called for unusable. It will mute it,
|
|
|
|
* shut it down, and unlist it via the DocManager. A fresh ActiveDoc can be acquired via the
|
|
|
|
* DocManager.
|
|
|
|
*/
|
2022-11-09 16:49:23 +00:00
|
|
|
public async replace(docSession: OptDocSession, source: DocReplacementOptions) {
|
2023-04-11 05:56:26 +00:00
|
|
|
if (parseUrlId(this._docName).snapshotId) {
|
|
|
|
throw new ApiError('Snapshots cannot be replaced.', 400);
|
|
|
|
}
|
2022-11-09 16:49:23 +00:00
|
|
|
if (!await this._granularAccess.isOwner(docSession)) {
|
|
|
|
throw new ApiError('Only owners can replace a document.', 403);
|
|
|
|
}
|
2023-04-12 16:18:48 +00:00
|
|
|
this._log.debug(docSession, 'ActiveDoc.replace starting shutdown');
|
2023-04-11 05:56:26 +00:00
|
|
|
|
|
|
|
// During replacement, it is important for all hands to be off the document. So we
|
|
|
|
// ask the shutdown method to do the replacement when the ActiveDoc is shutdown but
|
|
|
|
// before a new one could be opened.
|
2021-11-16 21:10:57 +00:00
|
|
|
return this.shutdown({
|
|
|
|
afterShutdown: () => this._docManager.storageManager.replace(this.docName, source)
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Finish initializing ActiveDoc, by initializing ActionHistory, Sharing, and docData.
|
|
|
|
*/
|
2021-10-01 13:45:27 +00:00
|
|
|
public async _initDoc(docSession: OptDocSession): Promise<void> {
|
|
|
|
const metaTableData = await this._tableMetadataLoader.fetchTablesAsActions();
|
2020-09-02 18:17:17 +00:00
|
|
|
this.docData = new DocData(tableId => this.fetchTable(makeExceptionalDocSession('system'), tableId), metaTableData);
|
2022-05-18 16:05:37 +00:00
|
|
|
this._onDemandActions = new OnDemandActions(this.docStorage, this.docData,
|
|
|
|
this._recoveryMode);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
await this._actionHistory.initialize();
|
2022-07-06 22:36:09 +00:00
|
|
|
this._granularAccess = new GranularAccess(this.docData, this.docStorage, this.docClients, (query) => {
|
2020-11-30 15:50:00 +00:00
|
|
|
return this._fetchQueryFromDB(query, false);
|
(core) Initial webhooks implementation
Summary:
See https://grist.quip.com/VKd3ASF99ezD/Outgoing-Webhooks
- 2 new DocApi endpoints: _subscribe and _unsubscribe, not meant to be user friendly or publicly documented. _unsubscribe should be given the response from _subscribe in the body, e.g:
```
$ curl -X POST -H "Authorization: Bearer 8fd4dc59ecb05ab29ae5a183c03101319b8e6ca9" "http://localhost:8080/api/docs/6WYa23FqWxGNe3AR6DLjCJ/tables/Table2/_subscribe" -H "Content-type: application/json" -d '{"url": "https://webhook.site/a916b526-8afc-46e6-aa8f-a625d0d83ec3", "eventTypes": ["add"], "isReadyColumn": "C"}'
{"unsubscribeKey":"3246f158-55b5-4fc7-baa5-093b75ffa86c","triggerId":2,"webhookId":"853b4bfa-9d39-4639-aa33-7d45354903c0"}
$ curl -X POST -H "Authorization: Bearer 8fd4dc59ecb05ab29ae5a183c03101319b8e6ca9" "http://localhost:8080/api/docs/6WYa23FqWxGNe3AR6DLjCJ/tables/Table2/_unsubscribe" -H "Content-type: application/json" -d '{"unsubscribeKey":"3246f158-55b5-4fc7-baa5-093b75ffa86c","triggerId":2,"webhookId":"853b4bfa-9d39-4639-aa33-7d45354903c0"}'
{"success":true}
```
- New DB entity Secret to hold the webhook URL and unsubscribe key
- New document metatable _grist_Triggers subscribes to table changes and points to a secret to use for a webhook
- New file Triggers.ts processes action summaries and uses the two new tables to send webhooks.
- Also went on a bit of a diversion and made a typesafe subclass of TableData for metatables.
I think this is essentially good enough for a first diff, to keep the diffs manageable and to talk about the overall structure. Future diffs can add tests and more robustness using redis etc. After this diff I can also start building the Zapier integration privately.
Test Plan: Tested manually: see curl commands in summary for an example. Payloads can be seen in https://webhook.site/#!/a916b526-8afc-46e6-aa8f-a625d0d83ec3/0b9fe335-33f7-49fe-b90b-2db5ba53382d/1 . Great site for testing webhooks btw.
Reviewers: dsagal, paulfitz
Reviewed By: paulfitz
Differential Revision: https://phab.getgrist.com/D3019
2021-09-22 23:06:23 +00:00
|
|
|
}, this.recoveryMode, this.getHomeDbManager(), this.docName);
|
2020-10-19 14:25:21 +00:00
|
|
|
await this._granularAccess.update();
|
2020-12-07 21:15:58 +00:00
|
|
|
this._sharing = new Sharing(this, this._actionHistory, this._modificationLock);
|
2021-10-01 13:45:27 +00:00
|
|
|
// Make sure there is at least one item in action history. The document will be perfectly
|
|
|
|
// functional without it, but comparing documents would need updating if history can
|
|
|
|
// be empty. For example, comparing an empty document immediately forked with the
|
|
|
|
// original would fail. So far, we have treated documents without a common history
|
|
|
|
// as incomparible, and we'd need to weaken that to allow comparisons with a document
|
|
|
|
// with nothing in action history.
|
|
|
|
if (this._actionHistory.getNextLocalActionNum() === 1) {
|
|
|
|
await this._actionHistory.recordNextShared({
|
|
|
|
userActions: [],
|
|
|
|
undo: [],
|
|
|
|
info: [0, this._makeInfo(makeExceptionalDocSession('system'))],
|
|
|
|
actionNum: 1,
|
|
|
|
actionHash: null, // set by ActionHistory
|
|
|
|
parentActionHash: null,
|
|
|
|
stored: [],
|
|
|
|
calc: [],
|
|
|
|
envelopes: [],
|
|
|
|
});
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
(core) Initial webhooks implementation
Summary:
See https://grist.quip.com/VKd3ASF99ezD/Outgoing-Webhooks
- 2 new DocApi endpoints: _subscribe and _unsubscribe, not meant to be user friendly or publicly documented. _unsubscribe should be given the response from _subscribe in the body, e.g:
```
$ curl -X POST -H "Authorization: Bearer 8fd4dc59ecb05ab29ae5a183c03101319b8e6ca9" "http://localhost:8080/api/docs/6WYa23FqWxGNe3AR6DLjCJ/tables/Table2/_subscribe" -H "Content-type: application/json" -d '{"url": "https://webhook.site/a916b526-8afc-46e6-aa8f-a625d0d83ec3", "eventTypes": ["add"], "isReadyColumn": "C"}'
{"unsubscribeKey":"3246f158-55b5-4fc7-baa5-093b75ffa86c","triggerId":2,"webhookId":"853b4bfa-9d39-4639-aa33-7d45354903c0"}
$ curl -X POST -H "Authorization: Bearer 8fd4dc59ecb05ab29ae5a183c03101319b8e6ca9" "http://localhost:8080/api/docs/6WYa23FqWxGNe3AR6DLjCJ/tables/Table2/_unsubscribe" -H "Content-type: application/json" -d '{"unsubscribeKey":"3246f158-55b5-4fc7-baa5-093b75ffa86c","triggerId":2,"webhookId":"853b4bfa-9d39-4639-aa33-7d45354903c0"}'
{"success":true}
```
- New DB entity Secret to hold the webhook URL and unsubscribe key
- New document metatable _grist_Triggers subscribes to table changes and points to a secret to use for a webhook
- New file Triggers.ts processes action summaries and uses the two new tables to send webhooks.
- Also went on a bit of a diversion and made a typesafe subclass of TableData for metatables.
I think this is essentially good enough for a first diff, to keep the diffs manageable and to talk about the overall structure. Future diffs can add tests and more robustness using redis etc. After this diff I can also start building the Zapier integration privately.
Test Plan: Tested manually: see curl commands in summary for an example. Payloads can be seen in https://webhook.site/#!/a916b526-8afc-46e6-aa8f-a625d0d83ec3/0b9fe335-33f7-49fe-b90b-2db5ba53382d/1 . Great site for testing webhooks btw.
Reviewers: dsagal, paulfitz
Reviewed By: paulfitz
Differential Revision: https://phab.getgrist.com/D3019
2021-09-22 23:06:23 +00:00
|
|
|
public getHomeDbManager() {
|
|
|
|
return this._docManager.getHomeDbManager();
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Adds a small table to start off a newly-created blank document.
|
|
|
|
*/
|
2020-09-02 18:17:17 +00:00
|
|
|
public addInitialTable(docSession: OptDocSession) {
|
2020-11-17 13:59:41 +00:00
|
|
|
// Use a non-client-specific session, so that this action is not part of anyone's undo history.
|
|
|
|
const newDocSession = makeExceptionalDocSession('nascent');
|
2022-05-04 09:54:30 +00:00
|
|
|
return this.applyUserActions(newDocSession, [["AddEmptyTable", null]]);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Imports files, removes previously created temporary hidden tables and creates the new ones.
|
|
|
|
* Param `prevTableIds` is an array of hiddenTableIds as received from previous `importFiles`
|
|
|
|
* call, or empty if there was no previous call.
|
|
|
|
*/
|
|
|
|
public importFiles(docSession: DocSession, dataSource: DataSourceTransformed,
|
|
|
|
parseOptions: ParseOptions, prevTableIds: string[]): Promise<ImportResult> {
|
|
|
|
return this._activeDocImport.importFiles(docSession, dataSource, parseOptions, prevTableIds);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Finishes import files, creates the new tables, and cleans up temporary hidden tables and uploads.
|
|
|
|
* Param `prevTableIds` is an array of hiddenTableIds as received from previous `importFiles`
|
|
|
|
* call, or empty if there was no previous call.
|
|
|
|
*/
|
|
|
|
public finishImportFiles(docSession: DocSession, dataSource: DataSourceTransformed,
|
2021-09-15 06:12:34 +00:00
|
|
|
prevTableIds: string[], importOptions: ImportOptions): Promise<ImportResult> {
|
|
|
|
return this._activeDocImport.finishImportFiles(docSession, dataSource, prevTableIds, importOptions);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Cancels import files, cleans up temporary hidden tables and uploads.
|
|
|
|
* Param `prevTableIds` is an array of hiddenTableIds as received from previous `importFiles`
|
|
|
|
* call, or empty if there was no previous call.
|
|
|
|
*/
|
2022-03-10 00:03:02 +00:00
|
|
|
public cancelImportFiles(docSession: DocSession, uploadId: number,
|
2020-07-21 13:20:51 +00:00
|
|
|
prevTableIds: string[]): Promise<void> {
|
2022-03-10 00:03:02 +00:00
|
|
|
return this._activeDocImport.cancelImportFiles(docSession, uploadId, prevTableIds);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2021-10-08 06:32:59 +00:00
|
|
|
/**
|
|
|
|
* Returns a diff of changes that will be applied to the destination table from `transformRule`
|
|
|
|
* if the data from `hiddenTableId` is imported with the specified `mergeOptions`.
|
|
|
|
*
|
|
|
|
* The diff is returned as a `DocStateComparison` of the same doc, with the `rightChanges`
|
|
|
|
* containing the updated cell values. Old values are pulled from the destination record (if
|
|
|
|
* a match was found), and new values are the result of merging in the new cell values with
|
|
|
|
* the merge strategy from `mergeOptions`.
|
|
|
|
*
|
|
|
|
* No distinction is currently made for added records vs. updated existing records; instead,
|
|
|
|
* we treat added records as an updated record in `hiddenTableId` where all the column
|
|
|
|
* values changed from blank to the original column values from `hiddenTableId`.
|
|
|
|
*/
|
|
|
|
public generateImportDiff(_docSession: DocSession, hiddenTableId: string, transformRule: TransformRule,
|
|
|
|
mergeOptions: MergeOptions): Promise<DocStateComparison> {
|
|
|
|
return this._activeDocImport.generateImportDiff(hiddenTableId, transformRule, mergeOptions);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Close the current document.
|
|
|
|
*/
|
|
|
|
public async closeDoc(docSession: DocSession): Promise<void> {
|
|
|
|
// Note that it's async only to satisfy the Rpc interface that expects a promise.
|
|
|
|
this.docClients.removeClient(docSession);
|
|
|
|
|
|
|
|
// If no more clients, schedule a shutdown.
|
|
|
|
if (this.docClients.clientCount() === 0) {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "will self-close in %d ms", this._inactivityTimer.getDelay());
|
2020-07-21 13:20:51 +00:00
|
|
|
this._inactivityTimer.enable();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Import the given upload as new tables in one step.
|
|
|
|
*/
|
|
|
|
@ActiveDoc.keepDocOpen
|
|
|
|
public async oneStepImport(docSession: OptDocSession, uploadInfo: UploadInfo): Promise<void> {
|
|
|
|
await this._activeDocImport.oneStepImport(docSession, uploadInfo);
|
|
|
|
}
|
|
|
|
|
2023-07-12 13:57:02 +00:00
|
|
|
/**
|
|
|
|
* Import data resulting from parsing a file into a new table.
|
|
|
|
* In normal circumstances this is only used internally.
|
|
|
|
* It's exposed publicly for use by grist-static which doesn't use the plugin system.
|
|
|
|
*/
|
|
|
|
public async importParsedFileAsNewTable(
|
|
|
|
docSession: OptDocSession, optionsAndData: ParseFileResult, importOptions: FileImportOptions
|
|
|
|
): Promise<ImportResult> {
|
|
|
|
return this._activeDocImport.importParsedFileAsNewTable(docSession, optionsAndData, importOptions);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* This function saves attachments from a given upload and creates an entry for them in the database.
|
|
|
|
* It returns the list of rowIds for the rows created in the _grist_Attachments table.
|
|
|
|
*/
|
2020-09-02 18:17:17 +00:00
|
|
|
public async addAttachments(docSession: OptDocSession, uploadId: number): Promise<number[]> {
|
|
|
|
const userId = getDocSessionUserId(docSession);
|
2020-07-21 13:20:51 +00:00
|
|
|
const upload: UploadInfo = globalUploadSet.getUploadInfo(uploadId, this.makeAccessId(userId));
|
|
|
|
try {
|
2022-05-03 05:20:31 +00:00
|
|
|
// We'll assert that the upload won't cause limits to be exceeded, retrying once after
|
|
|
|
// soft-deleting any unused attachments.
|
|
|
|
await retryOnce(
|
|
|
|
() => this._assertUploadSizeBelowLimit(upload),
|
|
|
|
async (e) => {
|
|
|
|
if (!(e instanceof LimitExceededError)) { throw e; }
|
|
|
|
|
|
|
|
// Check if any attachments are unused and can be soft-deleted to reduce the existing
|
|
|
|
// total size. We could do this from the beginning, but updateUsedAttachmentsIfNeeded
|
|
|
|
// is potentially expensive, so this optimises for the common case of not exceeding the limit.
|
|
|
|
const hadChanges = await this.updateUsedAttachmentsIfNeeded();
|
|
|
|
if (hadChanges) {
|
2022-05-16 17:41:12 +00:00
|
|
|
await this._updateAttachmentsSize({syncUsageToDatabase: false});
|
2022-05-03 05:20:31 +00:00
|
|
|
} else {
|
|
|
|
// No point in retrying if nothing changed.
|
|
|
|
throw new LimitExceededError("Exceeded attachments limit for document");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
2020-07-21 13:20:51 +00:00
|
|
|
const userActions: UserAction[] = await Promise.all(
|
|
|
|
upload.files.map(file => this._prepAttachment(docSession, file)));
|
2022-11-22 14:15:18 +00:00
|
|
|
const result = await this._applyUserActionsWithExtendedOptions(docSession, userActions, {
|
|
|
|
attachment: true,
|
|
|
|
});
|
2022-05-03 05:20:31 +00:00
|
|
|
this._updateAttachmentsSize().catch(e => {
|
|
|
|
this._log.warn(docSession, 'failed to update attachments size', e);
|
|
|
|
});
|
2022-11-15 14:37:48 +00:00
|
|
|
await this._granularAccess.noteUploads(docSession, result.retValues);
|
2020-07-21 13:20:51 +00:00
|
|
|
return result.retValues;
|
|
|
|
} finally {
|
|
|
|
await globalUploadSet.cleanup(uploadId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the record from _grist_Attachments table for the given attachment ID,
|
|
|
|
* or throws an error if not found.
|
|
|
|
*/
|
2022-07-06 22:36:09 +00:00
|
|
|
public getAttachmentMetadata(attId: number): MetaRowRecord<'_grist_Attachments'> {
|
2020-07-21 13:20:51 +00:00
|
|
|
// docData should always be available after loadDoc() or createDoc().
|
|
|
|
if (!this.docData) {
|
|
|
|
throw new Error("No doc data");
|
|
|
|
}
|
2022-07-06 22:36:09 +00:00
|
|
|
const attRecord = this.docData.getMetaTable('_grist_Attachments').getRecord(attId);
|
2020-07-21 13:20:51 +00:00
|
|
|
if (!attRecord) {
|
|
|
|
throw new ApiError(`Attachment not found: ${attId}`, 404);
|
|
|
|
}
|
|
|
|
return attRecord;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-07-06 22:36:09 +00:00
|
|
|
* Given a _gristAttachments record, returns a promise for the attachment data.
|
2022-11-15 14:37:48 +00:00
|
|
|
* Can optionally take a cell in which the attachment is expected to be
|
|
|
|
* referenced, and/or a `maybeNew` flag which, when set, specifies that the
|
|
|
|
* attachment may be a recent upload that is not yet referenced in the document.
|
2020-07-21 13:20:51 +00:00
|
|
|
* @returns {Promise<Buffer>} Promise for the data of this attachment; rejected on error.
|
|
|
|
*/
|
2022-07-06 22:36:09 +00:00
|
|
|
public async getAttachmentData(docSession: OptDocSession, attRecord: MetaRowRecord<"_grist_Attachments">,
|
2022-11-15 14:37:48 +00:00
|
|
|
options?: {
|
|
|
|
cell?: SingleCell,
|
|
|
|
maybeNew?: boolean,
|
|
|
|
}): Promise<Buffer> {
|
2022-07-06 22:36:09 +00:00
|
|
|
const attId = attRecord.id;
|
|
|
|
const fileIdent = attRecord.fileIdent;
|
2022-11-15 14:37:48 +00:00
|
|
|
const cell = options?.cell;
|
|
|
|
const maybeNew = options?.maybeNew;
|
2022-07-06 22:36:09 +00:00
|
|
|
if (
|
|
|
|
await this._granularAccess.canReadEverything(docSession) ||
|
|
|
|
await this.canDownload(docSession)
|
|
|
|
) {
|
|
|
|
// Do not need to sweat over access to attachments if user can
|
|
|
|
// read everything or download everything.
|
|
|
|
} else {
|
2022-11-15 14:37:48 +00:00
|
|
|
if (maybeNew && await this._granularAccess.isAttachmentUploadedByUser(docSession, attId)) {
|
|
|
|
// Fine, this is an attachment the user uploaded (recently).
|
|
|
|
} else if (cell) {
|
|
|
|
// Only provide the download if the user has access to the cell
|
|
|
|
// they specified, and that cell is in an attachment column,
|
|
|
|
// and the cell contains the specified attachment.
|
|
|
|
await this._granularAccess.assertAttachmentAccess(docSession, cell, attId);
|
|
|
|
} else {
|
|
|
|
if (!await this._granularAccess.findAttachmentCellForUser(docSession, attId)) {
|
|
|
|
// We found no reason to allow this user to access the attachment.
|
|
|
|
throw new ApiError('Cannot access attachment', 403);
|
2022-07-06 22:36:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
const data = await this.docStorage.getFileData(fileIdent);
|
|
|
|
if (!data) { throw new ApiError("Invalid attachment identifier", 404); }
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "getAttachment: %s -> %s bytes", fileIdent, data.length);
|
2020-07-21 13:20:51 +00:00
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Fetches the meta tables to return to the client when first opening a document.
|
|
|
|
*/
|
2020-09-02 18:17:17 +00:00
|
|
|
public async fetchMetaTables(docSession: OptDocSession) {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "fetchMetaTables");
|
2020-07-21 13:20:51 +00:00
|
|
|
if (!this.docData) { throw new Error("No doc data"); }
|
|
|
|
// Get metadata from local cache rather than data engine, so that we can
|
|
|
|
// still get it even if data engine is busy calculating.
|
|
|
|
const tables: {[key: string]: TableDataAction} = {};
|
|
|
|
for (const [tableId, tableData] of this.docData.getTables().entries()) {
|
|
|
|
if (!tableId.startsWith('_grist_')) { continue; }
|
|
|
|
tables[tableId] = tableData.getTableDataAction();
|
|
|
|
}
|
2020-09-11 20:27:09 +00:00
|
|
|
return this._granularAccess.filterMetaTables(docSession, tables);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Makes sure document is completely initialized. May throw if doc is broken.
|
|
|
|
*/
|
|
|
|
public async waitForInitialization() {
|
2022-03-24 20:27:34 +00:00
|
|
|
await this._initializationPromise;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2020-09-11 20:27:09 +00:00
|
|
|
// Check if user has rights to download this doc.
|
2020-12-11 19:22:35 +00:00
|
|
|
public async canDownload(docSession: OptDocSession) {
|
2021-01-12 15:48:40 +00:00
|
|
|
return this._granularAccess.canCopyEverything(docSession);
|
2020-09-11 20:27:09 +00:00
|
|
|
}
|
|
|
|
|
2023-09-04 13:21:18 +00:00
|
|
|
// Check if user has rights to read everything in this doc.
|
|
|
|
public async canCopyEverything(docSession: OptDocSession) {
|
|
|
|
return this._granularAccess.canCopyEverything(docSession);
|
|
|
|
}
|
|
|
|
|
2021-07-20 20:20:31 +00:00
|
|
|
// Check if it is appropriate for the user to be treated as an owner of
|
|
|
|
// the document for granular access purposes when in "prefork" mode
|
|
|
|
// (meaning a document has been opened with the intent to fork it, but
|
|
|
|
// an initial modification has not yet been made).
|
|
|
|
// Currently, we decide it is appropriate if the user has access to all
|
|
|
|
// the data in the document, either directly or via the special
|
|
|
|
// "FullCopies" permission.
|
|
|
|
public async canForkAsOwner(docSession: OptDocSession) {
|
|
|
|
return this._granularAccess.canCopyEverything(docSession);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove cached access information for a given session.
|
|
|
|
public flushAccess(docSession: OptDocSession) {
|
|
|
|
return this._granularAccess.flushAccess(docSession);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Fetches a particular table from the data engine to return to the client.
|
|
|
|
* @param {String} tableId: The string identifier of the table.
|
|
|
|
* @param {Boolean} waitForFormulas: If true, wait for all data to be loaded/calculated.
|
|
|
|
* @returns {Promise} Promise for the TableData object, which is a BulkAddRecord-like array of the
|
|
|
|
* form of the form ["TableData", table_id, row_ids, column_values].
|
|
|
|
*/
|
2020-09-02 18:17:17 +00:00
|
|
|
public async fetchTable(docSession: OptDocSession, tableId: string,
|
2022-12-21 16:40:00 +00:00
|
|
|
waitForFormulas: boolean = false): Promise<TableFetchResult> {
|
2020-07-21 13:20:51 +00:00
|
|
|
return this.fetchQuery(docSession, {tableId, filters: {}}, waitForFormulas);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Fetches data according to the given query, which includes tableId and filters (see Query in
|
|
|
|
* app/common/ActiveDocAPI.ts). The data is fetched from the data engine for regular tables, or
|
|
|
|
* from the DocStorage directly for onDemand tables.
|
|
|
|
* @param {Boolean} waitForFormulas: If true, wait for all data to be loaded/calculated. If false,
|
|
|
|
* special "pending" values may be returned.
|
|
|
|
*/
|
2021-08-10 18:21:03 +00:00
|
|
|
public async fetchQuery(docSession: OptDocSession, query: ServerQuery,
|
2022-12-21 16:40:00 +00:00
|
|
|
waitForFormulas: boolean = false): Promise<TableFetchResult> {
|
2020-07-21 13:20:51 +00:00
|
|
|
this._inactivityTimer.ping(); // The doc is in active use; ping it to stay open longer.
|
|
|
|
|
2020-09-11 20:27:09 +00:00
|
|
|
// If user does not have rights to access what this query is asking for, fail.
|
2020-12-11 19:22:35 +00:00
|
|
|
const tableAccess = await this._granularAccess.getTableAccess(docSession, query.tableId);
|
2021-02-15 21:36:33 +00:00
|
|
|
|
|
|
|
this._granularAccess.assertCanRead(tableAccess);
|
2020-09-11 20:27:09 +00:00
|
|
|
|
2021-07-30 14:10:54 +00:00
|
|
|
if (query.tableId.startsWith('_gristsys_')) {
|
|
|
|
throw new Error('Cannot fetch _gristsys tables');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (query.tableId.startsWith('_grist_') && !await this._granularAccess.canReadEverything(docSession)) {
|
|
|
|
// Metadata tables may need filtering, and this can't be done by looking at a single
|
|
|
|
// table. So we pick out the table we want from fetchMetaTables (which has applied
|
|
|
|
// filtering).
|
|
|
|
const tables = await this.fetchMetaTables(docSession);
|
2022-12-21 16:40:00 +00:00
|
|
|
const tableData = tables[query.tableId];
|
|
|
|
if (tableData) { return {tableData}; }
|
2021-07-30 14:10:54 +00:00
|
|
|
// If table not found, continue, to give a consistent error for a table not found.
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Some tests read _grist_ tables via the api. The _fetchQueryFromDB method
|
|
|
|
// currently cannot read those tables, so we load them from the data engine
|
|
|
|
// when ready.
|
2020-10-12 13:50:07 +00:00
|
|
|
// Also, if row-level access is being controlled, we wait for formula columns
|
|
|
|
// to be populated.
|
|
|
|
const wantFull = waitForFormulas || query.tableId.startsWith('_grist_') ||
|
2021-02-15 21:36:33 +00:00
|
|
|
this._granularAccess.getReadPermission(tableAccess) === 'mixed';
|
2020-07-21 13:20:51 +00:00
|
|
|
const onDemand = this._onDemandActions.isOnDemand(query.tableId);
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "fetchQuery %s %s", JSON.stringify(query),
|
2020-07-21 13:20:51 +00:00
|
|
|
onDemand ? "(onDemand)" : "(regular)");
|
|
|
|
let data: TableDataAction;
|
2023-04-11 05:56:26 +00:00
|
|
|
if (onDemand || this._isSnapshot) {
|
2020-07-21 13:20:51 +00:00
|
|
|
data = await this._fetchQueryFromDB(query, onDemand);
|
|
|
|
} else if (wantFull) {
|
|
|
|
await this.waitForInitialization();
|
|
|
|
data = await this._fetchQueryFromDataEngine(query);
|
|
|
|
} else {
|
|
|
|
if (!this._fullyLoaded) {
|
|
|
|
data = await this._fetchQueryFromDB(query, false);
|
|
|
|
}
|
|
|
|
if (this._fullyLoaded) { // Already loaded or finished loading while fetching from DB
|
|
|
|
const key = JSON.stringify(query);
|
|
|
|
// TODO: cache longer if the underlying fetch takes longer to do.
|
|
|
|
data = await mapGetOrSet(this._fetchCache, key, () => this._fetchQueryFromDataEngine(query));
|
|
|
|
}
|
|
|
|
}
|
2020-10-12 13:50:07 +00:00
|
|
|
// If row-level access is being controlled, filter the data appropriately.
|
2020-11-03 23:44:09 +00:00
|
|
|
// Likewise if column-level access is being controlled.
|
2021-02-15 21:36:33 +00:00
|
|
|
if (this._granularAccess.getReadPermission(tableAccess) !== 'allow') {
|
2021-03-05 17:12:17 +00:00
|
|
|
data = cloneDeep(data!); // Clone since underlying fetch may be cached and shared.
|
|
|
|
await this._granularAccess.filterData(docSession, data);
|
2020-10-12 13:50:07 +00:00
|
|
|
}
|
2022-12-21 16:40:00 +00:00
|
|
|
|
|
|
|
// Consider whether we need to add attachment metadata.
|
|
|
|
// TODO: it might be desirable to always send attachment data, or allow
|
|
|
|
// this to be an option in api calls related to fetching.
|
|
|
|
let attachments: BulkAddRecord | undefined;
|
|
|
|
const attachmentColumns = this._getCachedAttachmentColumns();
|
|
|
|
if (attachmentColumns?.size && await this._granularAccess.needAttachmentControl(docSession)) {
|
|
|
|
const attIds = gatherAttachmentIds(attachmentColumns, data!);
|
|
|
|
if (attIds.size > 0) {
|
|
|
|
attachments = this.docData!.getMetaTable('_grist_Attachments')
|
|
|
|
.getBulkAddRecord([...attIds]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "fetchQuery -> %d rows, cols: %s",
|
2020-07-21 13:20:51 +00:00
|
|
|
data![2].length, Object.keys(data![3]).join(", "));
|
2022-12-21 16:40:00 +00:00
|
|
|
return {tableData: data!, ...(attachments && {attachments})};
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Fetches the generated schema for a given table.
|
|
|
|
* @param {String} tableId: The string identifier of the table.
|
|
|
|
* @returns {Promise} Promise for a string representing the generated table schema.
|
|
|
|
*/
|
|
|
|
public async fetchTableSchema(docSession: DocSession): Promise<string> {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "fetchTableSchema(%s)", docSession);
|
2021-05-27 13:18:57 +00:00
|
|
|
// Permit code view if user can read everything, or can download/copy (perhaps
|
|
|
|
// via an exceptional permission for sample documents)
|
|
|
|
if (!(await this._granularAccess.canReadEverything(docSession) ||
|
|
|
|
await this.canDownload(docSession))) {
|
|
|
|
throw new ApiError('Cannot view code, it may contain private material', 403);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.waitForInitialization();
|
2020-12-07 21:15:58 +00:00
|
|
|
return this._pyCall('fetch_table_schema');
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Makes a query (documented elsewhere) and subscribes to it, so that the client receives
|
|
|
|
* docActions that affect this query's results.
|
|
|
|
*/
|
2021-08-10 18:21:03 +00:00
|
|
|
public async useQuerySet(docSession: OptDocSession, query: ServerQuery): Promise<QueryResult> {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "useQuerySet(%s, %s)", docSession, query);
|
2020-07-21 13:20:51 +00:00
|
|
|
// TODO implement subscribing to the query.
|
|
|
|
// - Convert tableId+colIds to TableData/ColData references
|
|
|
|
// - Return a unique identifier for unsubscribing
|
|
|
|
// - Each call can create its own object, return own identifier.
|
|
|
|
// - Subscription should not be affected by renames (so don't hold on to query/tableId/colIds)
|
|
|
|
// - Table/column deletion should make subscription inactive, and unsubscribing an inactive
|
|
|
|
// subscription should not produce an error.
|
2022-12-21 16:40:00 +00:00
|
|
|
const tableFetchResult = await this.fetchQuery(docSession, query);
|
|
|
|
return {querySubId: 0, ...tableFetchResult};
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Removes all subscriptions to the given query from this client, so that it stops receiving
|
|
|
|
* docActions relevant only to this query.
|
|
|
|
*/
|
|
|
|
public async disposeQuerySet(docSession: DocSession, querySubId: number): Promise<void> {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "disposeQuerySet(%s, %s)", docSession, querySubId);
|
2020-07-21 13:20:51 +00:00
|
|
|
// TODO To-be-implemented
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the most likely target column in the document for the given column.
|
|
|
|
* @param {Array} values: An array of values to search for in columns in the document.
|
|
|
|
* @param {Number} n: Number of results to return.
|
|
|
|
* @param {String} optTableId: If a valid tableId, search only that table.
|
|
|
|
* @returns {Promise} Promise for an array of colRefs describing matching columns ordered from
|
|
|
|
* best to worst. Match quality is determined by searching only a sample of column data.
|
|
|
|
* See engine.py find_col_from_values for implementation.
|
|
|
|
*/
|
|
|
|
public async findColFromValues(docSession: DocSession, values: any[], n: number,
|
|
|
|
optTableId?: string): Promise<number[]> {
|
2021-03-25 17:37:09 +00:00
|
|
|
// This could leak information about private tables, so check for permission.
|
|
|
|
if (!await this._granularAccess.canScanData(docSession)) { return []; }
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "findColFromValues(%s, %s, %s)", docSession, values, n);
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.waitForInitialization();
|
2020-12-07 21:15:58 +00:00
|
|
|
return this._pyCall('find_col_from_values', values, n, optTableId);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2021-10-04 16:14:14 +00:00
|
|
|
/**
|
|
|
|
* Returns column metadata for all visible columns from `tableId`.
|
|
|
|
*
|
|
|
|
* @param {string} tableId Table to retrieve column metadata for.
|
|
|
|
* @returns {Promise<TableRecordValue[]>} Records containing metadata about the visible columns
|
|
|
|
* from `tableId`.
|
|
|
|
*/
|
2021-11-03 11:44:28 +00:00
|
|
|
public async getTableCols(
|
|
|
|
docSession: OptDocSession,
|
|
|
|
tableId: string,
|
(core) Improve API Console and link from Document Settings.
Summary:
Changes to building and serving:
- Remove unpkg dependencies, add npm module for swagger-ui-dist instead.
- Move apiconsole JS logic into core/app/client/apiconsole.ts, and use TypeScript.
- Add symlinks to swagger in static/ and core/static/.
- Refactor loadScript, and add loadCssFile; use these to load swagger-ui resources.
Changes to console itself:
- Support docId, workspaceId, orgId URL parameters. When present, the matching
value in dropdowns is moved to the front and marked as "(Current)".
- Fix the ordering of example values, particularly for workspaces.
- Remove unwanted example values.
- Hide confusing "Authorize" button.
- Hide API keys, and rely consistently on cookies for executing API calls.
Integration into Grist:
- Added a button to Document Settings, just under document ID in "API".
- The button opens a separate page, passing in org, workspace, and doc info for the current doc.
Test Plan: Only tested manually, no automated tests yet.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D4173
2024-01-27 04:21:34 +00:00
|
|
|
includeHidden = false): Promise<RecordWithStringId[]> {
|
2021-10-04 16:14:14 +00:00
|
|
|
const metaTables = await this.fetchMetaTables(docSession);
|
|
|
|
const tableRef = tableIdToRef(metaTables, tableId);
|
|
|
|
const [, , colRefs, columnData] = metaTables._grist_Tables_column;
|
|
|
|
|
|
|
|
// colId is pulled out of fields and used as the root id
|
|
|
|
const fieldNames = without(Object.keys(columnData), "colId");
|
|
|
|
|
(core) Improve API Console and link from Document Settings.
Summary:
Changes to building and serving:
- Remove unpkg dependencies, add npm module for swagger-ui-dist instead.
- Move apiconsole JS logic into core/app/client/apiconsole.ts, and use TypeScript.
- Add symlinks to swagger in static/ and core/static/.
- Refactor loadScript, and add loadCssFile; use these to load swagger-ui resources.
Changes to console itself:
- Support docId, workspaceId, orgId URL parameters. When present, the matching
value in dropdowns is moved to the front and marked as "(Current)".
- Fix the ordering of example values, particularly for workspaces.
- Remove unwanted example values.
- Hide confusing "Authorize" button.
- Hide API keys, and rely consistently on cookies for executing API calls.
Integration into Grist:
- Added a button to Document Settings, just under document ID in "API".
- The button opens a separate page, passing in org, workspace, and doc info for the current doc.
Test Plan: Only tested manually, no automated tests yet.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D4173
2024-01-27 04:21:34 +00:00
|
|
|
const columns: RecordWithStringId[] = [];
|
2021-10-04 16:14:14 +00:00
|
|
|
(columnData.colId as string[]).forEach((id, index) => {
|
2021-11-03 11:44:28 +00:00
|
|
|
const hasNoId = !id;
|
|
|
|
const isHidden = hasNoId || id === "manualSort" || id.startsWith("gristHelper_");
|
|
|
|
const fromDifferentTable = columnData.parentId[index] !== tableRef;
|
|
|
|
const skip = (isHidden && !includeHidden) || hasNoId || fromDifferentTable;
|
|
|
|
if (skip) {
|
2021-10-04 16:14:14 +00:00
|
|
|
return;
|
|
|
|
}
|
(core) Improve API Console and link from Document Settings.
Summary:
Changes to building and serving:
- Remove unpkg dependencies, add npm module for swagger-ui-dist instead.
- Move apiconsole JS logic into core/app/client/apiconsole.ts, and use TypeScript.
- Add symlinks to swagger in static/ and core/static/.
- Refactor loadScript, and add loadCssFile; use these to load swagger-ui resources.
Changes to console itself:
- Support docId, workspaceId, orgId URL parameters. When present, the matching
value in dropdowns is moved to the front and marked as "(Current)".
- Fix the ordering of example values, particularly for workspaces.
- Remove unwanted example values.
- Hide confusing "Authorize" button.
- Hide API keys, and rely consistently on cookies for executing API calls.
Integration into Grist:
- Added a button to Document Settings, just under document ID in "API".
- The button opens a separate page, passing in org, workspace, and doc info for the current doc.
Test Plan: Only tested manually, no automated tests yet.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D4173
2024-01-27 04:21:34 +00:00
|
|
|
const column: RecordWithStringId = { id, fields: { colRef: colRefs[index] } };
|
2021-10-04 16:14:14 +00:00
|
|
|
for (const key of fieldNames) {
|
|
|
|
column.fields[key] = columnData[key][index];
|
|
|
|
}
|
|
|
|
columns.push(column);
|
|
|
|
});
|
|
|
|
return columns;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Returns error message (traceback) for one invalid formula cell.
|
|
|
|
* @param {String} tableId - Table name
|
|
|
|
* @param {String} colId - Column name
|
|
|
|
* @param {Integer} rowId - Row number
|
|
|
|
* @returns {Promise} Promise for a error message
|
|
|
|
*/
|
2023-05-08 18:15:22 +00:00
|
|
|
public async getFormulaError(docSession: OptDocSession, tableId: string, colId: string,
|
2020-07-21 13:20:51 +00:00
|
|
|
rowId: number): Promise<CellValue> {
|
2022-07-14 11:29:22 +00:00
|
|
|
// Throw an error if the user doesn't have access to read this cell.
|
|
|
|
await this._granularAccess.getCellValue(docSession, {tableId, colId, rowId});
|
|
|
|
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "getFormulaError(%s, %s, %s, %s)",
|
2020-07-21 13:20:51 +00:00
|
|
|
docSession, tableId, colId, rowId);
|
|
|
|
await this.waitForInitialization();
|
2020-12-07 21:15:58 +00:00
|
|
|
return this._pyCall('get_formula_error', tableId, colId, rowId);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Applies an array of user actions received from a browser client.
|
|
|
|
*
|
|
|
|
* @param {Object} docSession: The client session originating this action.
|
|
|
|
* @param {Array} action: The user action to apply, e.g. ["UpdateRecord", tableId, rowId, etc].
|
|
|
|
* @param {Object} options: See _applyUserActions for documentation
|
|
|
|
* @returns {Promise:Array[Object]} Promise that's resolved when action is applied successfully.
|
|
|
|
* The array includes the retValue objects for each
|
|
|
|
* actionGroup.
|
|
|
|
*/
|
|
|
|
public async applyUserActions(docSession: OptDocSession, actions: UserAction[],
|
2022-11-15 14:37:48 +00:00
|
|
|
unsanitizedOptions?: ApplyUAOptions): Promise<ApplyUAResult> {
|
|
|
|
const options = sanitizeApplyUAOptions(unsanitizedOptions);
|
|
|
|
return this._applyUserActionsWithExtendedOptions(docSession, actions, options);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A variant of applyUserActions where actions are passed in by ids (actionNum, actionHash)
|
|
|
|
* rather than by value.
|
|
|
|
*
|
|
|
|
* @param docSession: The client session originating this action.
|
|
|
|
* @param actionNums: The user actions to do/undo, by actionNum.
|
|
|
|
* @param actionHashes: actionHash checksums for each listed actionNum.
|
|
|
|
* @param undo: Whether the actions are to be undone.
|
|
|
|
* @param options: As for applyUserActions.
|
|
|
|
* @returns Promise of retValues, see applyUserActions.
|
|
|
|
*/
|
2023-03-01 20:43:22 +00:00
|
|
|
public async applyUserActionsById(docSession: OptDocSession,
|
2020-07-21 13:20:51 +00:00
|
|
|
actionNums: number[],
|
|
|
|
actionHashes: string[],
|
|
|
|
undo: boolean,
|
2022-11-15 14:37:48 +00:00
|
|
|
unsanitizedOptions?: ApplyUAOptions): Promise<ApplyUAResult> {
|
|
|
|
const options = sanitizeApplyUAOptions(unsanitizedOptions);
|
2020-07-21 13:20:51 +00:00
|
|
|
const actionBundles = await this._actionHistory.getActions(actionNums);
|
2022-11-15 14:37:48 +00:00
|
|
|
let fromOwnHistory: boolean = true;
|
|
|
|
const user = getDocSessionUser(docSession);
|
|
|
|
let oldestSource: number = Date.now();
|
2020-07-21 13:20:51 +00:00
|
|
|
for (const [index, bundle] of actionBundles.entries()) {
|
|
|
|
const actionNum = actionNums[index];
|
|
|
|
const actionHash = actionHashes[index];
|
|
|
|
if (!bundle) { throw new Error(`Could not find actionNum ${actionNum}`); }
|
2022-11-15 14:37:48 +00:00
|
|
|
const info = bundle.info[1];
|
|
|
|
const bundleEmail = info.user || '';
|
|
|
|
const sessionEmail = user?.email || '';
|
|
|
|
if (normalizeEmail(sessionEmail) !== normalizeEmail(bundleEmail)) {
|
|
|
|
fromOwnHistory = false;
|
|
|
|
}
|
|
|
|
if (info.time && info.time < oldestSource) {
|
|
|
|
oldestSource = info.time;
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
if (actionHash !== bundle.actionHash) {
|
|
|
|
throw new Error(`Hash mismatch for actionNum ${actionNum}: ` +
|
|
|
|
`expected ${actionHash} but got ${bundle.actionHash}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let actions: UserAction[];
|
|
|
|
if (undo) {
|
|
|
|
actions = [['ApplyUndoActions', flatten(actionBundles.map(a => a!.undo))]];
|
|
|
|
} else {
|
|
|
|
actions = flatten(actionBundles.map(a => a!.userActions));
|
|
|
|
}
|
2020-09-11 20:27:09 +00:00
|
|
|
// Granular access control implemented ultimately in _applyUserActions.
|
|
|
|
// It could be that error cases and timing etc leak some info prior to this
|
|
|
|
// point.
|
2021-06-09 19:31:59 +00:00
|
|
|
// Undos are best effort now by default.
|
2022-11-15 14:37:48 +00:00
|
|
|
return this._applyUserActionsWithExtendedOptions(
|
|
|
|
docSession, actions, {bestEffort: undo,
|
|
|
|
oldestSource,
|
|
|
|
fromOwnHistory, ...(options||{})});
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Called by Sharing class for every LocalActionBundle (of our own actions) that gets applied.
|
|
|
|
*/
|
|
|
|
public async processActionBundle(localActionBundle: LocalActionBundle): Promise<void> {
|
|
|
|
const docData = this.docData;
|
|
|
|
if (!docData) { return; } // Happens on doc creation while processing InitNewDoc action.
|
|
|
|
localActionBundle.stored.forEach(da => docData.receiveAction(da[1]));
|
|
|
|
localActionBundle.calc.forEach(da => docData.receiveAction(da[1]));
|
|
|
|
const docActions = getEnvContent(localActionBundle.stored);
|
|
|
|
if (docActions.some(docAction => this._onDemandActions.isSchemaAction(docAction))) {
|
|
|
|
const indexes = this._onDemandActions.getDesiredIndexes();
|
|
|
|
await this.docStorage.updateIndexes(indexes);
|
2020-12-11 19:22:35 +00:00
|
|
|
// TODO: should probably add indexes for user attribute tables.
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
2022-12-21 16:40:00 +00:00
|
|
|
if (docActions.some(docAction => isSchemaAction(docAction))) {
|
|
|
|
this._attachmentColumns = undefined;
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Used by tests to force an update indexes. We don't otherwise update indexes until
|
|
|
|
* there is a schema change.
|
|
|
|
*/
|
|
|
|
public async testUpdateIndexes() {
|
|
|
|
const indexes = this._onDemandActions.getDesiredIndexes();
|
|
|
|
await this.docStorage.updateIndexes(indexes);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async removeInstanceFromDoc(docSession: DocSession): Promise<void> {
|
2020-11-12 04:56:05 +00:00
|
|
|
await this._sharing.removeInstanceFromDoc();
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2020-09-02 18:17:17 +00:00
|
|
|
public async renameDocTo(docSession: OptDocSession, newName: string): Promise<void> {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, 'renameDoc', newName);
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.docStorage.renameDocTo(newName);
|
|
|
|
this._docName = newName;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Initiates user actions bandling for undo.
|
|
|
|
*/
|
|
|
|
public startBundleUserActions(docSession: OptDocSession) {
|
|
|
|
if (!docSession.shouldBundleActions) {
|
|
|
|
docSession.shouldBundleActions = true;
|
|
|
|
docSession.linkId = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Stops user actions bandling for undo.
|
|
|
|
*/
|
|
|
|
public stopBundleUserActions(docSession: OptDocSession) {
|
|
|
|
docSession.shouldBundleActions = false;
|
|
|
|
docSession.linkId = 0;
|
|
|
|
}
|
|
|
|
|
(core) Show example values in formula autocomplete
Summary:
This diff adds a preview of the value of certain autocomplete suggestions, especially of the form `$foo.bar` or `user.email`. The main initial motivation was to show the difference between `$Ref` and `$Ref.DisplayCol`, but the feature is more general.
The client now sends the row ID of the row being edited (along with the table and column IDs which were already sent) to the server to fetch autocomplete suggestions. The returned suggestions are now tuples `(suggestion, example_value)` where `example_value` is a string or null. The example value is simply obtained by evaluating (in a controlled way) the suggestion in the context of the given record and the current user. The string representation is similar to the standard `repr` but dates and datetimes are formatted, and the whole thing is truncated for efficiency.
The example values are shown in the autocomplete popup separated from the actual suggestion by a number of spaces calculated to:
1. Clearly separate the suggestion from the values
2. Left-align the example values in most cases
3. Avoid having so much space such that connecting suggestions and values becomes visually difficult.
The tokenization of the row is then tweaked to show the example in light grey to deemphasise it.
Main discussion where the above was decided: https://grist.slack.com/archives/CDHABLZJT/p1661795588100009
The diff also includes various other small improvements and fixes:
- The autocomplete popup is much wider to make room for long suggestions, particularly lookups, as pointed out in https://phab.getgrist.com/D3580#inline-41007. The wide popup is the reason a fancy solution was needed to position the example values. I didn't see a way to dynamically resize the popup based on suggestions, and it didn't seem like a good idea to try.
- The `grist` and `python` labels previously shown on the right are removed. They were not helpful (https://grist.slack.com/archives/CDHABLZJT/p1659697086155179) and would get in the way of the example values.
- Fixed a bug in our custom tokenization that caused function arguments to be weirdly truncated in the middle: https://grist.slack.com/archives/CDHABLZJT/p1661956353699169?thread_ts=1661953258.342739&cid=CDHABLZJT and https://grist.slack.com/archives/C069RUP71/p1659696778991339
- Hide suggestions involving helper columns like `$gristHelper_Display` or `Table.lookupRecords(gristHelper_Display=` (https://grist.slack.com/archives/CDHABLZJT/p1661953258342739). The former has been around for a while and seems to be a mistake. The fix is simply to use `is_visible_column` instead of `is_user_column`. Since the latter is not used anywhere else, and using it in the first place seems like a mistake more than anything else, I've also removed the function to prevent similar mistakes in the future.
- Don't suggest private columns as lookup arguments: https://grist.slack.com/archives/CDHABLZJT/p1662133416652499?thread_ts=1661795588.100009&cid=CDHABLZJT
- Only fetch fresh suggestions specifically after typing `lookupRecords(` or `lookupOne(` rather than just `(`, as this would needlessly hide function suggestions which could still be useful to see the arguments. However this only makes a difference when there are still multiple matching suggestions, otherwise Ace hides them anyway.
Test Plan: Extended and updated several Python and browser tests.
Reviewers: paulfitz
Reviewed By: paulfitz
Differential Revision: https://phab.getgrist.com/D3611
2022-09-28 14:47:55 +00:00
|
|
|
public async autocomplete(
|
|
|
|
docSession: DocSession, txt: string, tableId: string, columnId: string, rowId: UIRowId
|
|
|
|
): Promise<ISuggestionWithValue[]> {
|
2020-09-11 20:27:09 +00:00
|
|
|
// Autocompletion can leak names of tables and columns.
|
2021-03-25 17:37:09 +00:00
|
|
|
if (!await this._granularAccess.canScanData(docSession)) { return []; }
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.waitForInitialization();
|
2021-07-15 00:45:53 +00:00
|
|
|
const user = await this._granularAccess.getCachedUser(docSession);
|
(core) Show example values in formula autocomplete
Summary:
This diff adds a preview of the value of certain autocomplete suggestions, especially of the form `$foo.bar` or `user.email`. The main initial motivation was to show the difference between `$Ref` and `$Ref.DisplayCol`, but the feature is more general.
The client now sends the row ID of the row being edited (along with the table and column IDs which were already sent) to the server to fetch autocomplete suggestions. The returned suggestions are now tuples `(suggestion, example_value)` where `example_value` is a string or null. The example value is simply obtained by evaluating (in a controlled way) the suggestion in the context of the given record and the current user. The string representation is similar to the standard `repr` but dates and datetimes are formatted, and the whole thing is truncated for efficiency.
The example values are shown in the autocomplete popup separated from the actual suggestion by a number of spaces calculated to:
1. Clearly separate the suggestion from the values
2. Left-align the example values in most cases
3. Avoid having so much space such that connecting suggestions and values becomes visually difficult.
The tokenization of the row is then tweaked to show the example in light grey to deemphasise it.
Main discussion where the above was decided: https://grist.slack.com/archives/CDHABLZJT/p1661795588100009
The diff also includes various other small improvements and fixes:
- The autocomplete popup is much wider to make room for long suggestions, particularly lookups, as pointed out in https://phab.getgrist.com/D3580#inline-41007. The wide popup is the reason a fancy solution was needed to position the example values. I didn't see a way to dynamically resize the popup based on suggestions, and it didn't seem like a good idea to try.
- The `grist` and `python` labels previously shown on the right are removed. They were not helpful (https://grist.slack.com/archives/CDHABLZJT/p1659697086155179) and would get in the way of the example values.
- Fixed a bug in our custom tokenization that caused function arguments to be weirdly truncated in the middle: https://grist.slack.com/archives/CDHABLZJT/p1661956353699169?thread_ts=1661953258.342739&cid=CDHABLZJT and https://grist.slack.com/archives/C069RUP71/p1659696778991339
- Hide suggestions involving helper columns like `$gristHelper_Display` or `Table.lookupRecords(gristHelper_Display=` (https://grist.slack.com/archives/CDHABLZJT/p1661953258342739). The former has been around for a while and seems to be a mistake. The fix is simply to use `is_visible_column` instead of `is_user_column`. Since the latter is not used anywhere else, and using it in the first place seems like a mistake more than anything else, I've also removed the function to prevent similar mistakes in the future.
- Don't suggest private columns as lookup arguments: https://grist.slack.com/archives/CDHABLZJT/p1662133416652499?thread_ts=1661795588.100009&cid=CDHABLZJT
- Only fetch fresh suggestions specifically after typing `lookupRecords(` or `lookupOne(` rather than just `(`, as this would needlessly hide function suggestions which could still be useful to see the arguments. However this only makes a difference when there are still multiple matching suggestions, otherwise Ace hides them anyway.
Test Plan: Extended and updated several Python and browser tests.
Reviewers: paulfitz
Reviewed By: paulfitz
Differential Revision: https://phab.getgrist.com/D3611
2022-09-28 14:47:55 +00:00
|
|
|
return this._pyCall('autocomplete', txt, tableId, columnId, rowId, user.toJSON());
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2023-07-05 15:36:45 +00:00
|
|
|
// Callback to generate a prompt containing schema info for assistance.
|
|
|
|
public async assistanceSchemaPromptV1(
|
|
|
|
docSession: OptDocSession, options: AssistanceSchemaPromptV1Context): Promise<string> {
|
2023-05-08 18:15:22 +00:00
|
|
|
// Making a prompt leaks names of tables and columns etc.
|
2023-02-08 15:46:34 +00:00
|
|
|
if (!await this._granularAccess.canScanData(docSession)) {
|
|
|
|
throw new Error("Permission denied");
|
|
|
|
}
|
2023-07-05 15:36:45 +00:00
|
|
|
return await this._pyCall('get_formula_prompt', options.tableId, options.colId, options.docString);
|
2023-05-08 18:15:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Callback to make a data-engine formula tweak for assistance.
|
|
|
|
public assistanceFormulaTweak(txt: string) {
|
|
|
|
return this._pyCall('convert_formula_completion', txt);
|
|
|
|
}
|
|
|
|
|
2023-07-24 18:56:38 +00:00
|
|
|
// Callback to compute an existing formula and return the result along with recorded values
|
|
|
|
// of (possibly nested) attributes of `rec`.
|
|
|
|
// Used by AI assistance to fix an incorrect formula.
|
|
|
|
public assistanceEvaluateFormula(options: AssistanceContext) {
|
|
|
|
if (!options.evaluateCurrentFormula) {
|
|
|
|
throw new Error('evaluateCurrentFormula must be true');
|
|
|
|
}
|
|
|
|
return this._pyCall('evaluate_formula', options.tableId, options.colId, options.rowId);
|
|
|
|
}
|
|
|
|
|
2021-09-30 08:19:22 +00:00
|
|
|
public fetchURL(docSession: DocSession, url: string, options?: FetchUrlOptions): Promise<UploadResult> {
|
|
|
|
return fetchURL(url, this.makeAccessId(docSession.authorizer.getUserId()), options);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2021-03-02 21:11:37 +00:00
|
|
|
public async forwardPluginRpc(docSession: DocSession, pluginId: string, msg: IMessage): Promise<any> {
|
|
|
|
if (await this._granularAccess.hasNuancedAccess(docSession)) {
|
2020-09-11 20:27:09 +00:00
|
|
|
throw new Error('cannot confirm access to plugin');
|
|
|
|
}
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
if (!this.docPluginManager) { throw new Error('no plugin manager available'); }
|
2020-07-21 13:20:51 +00:00
|
|
|
const pluginRpc = this.docPluginManager.plugins[pluginId].rpc;
|
|
|
|
switch (msg.mtype) {
|
|
|
|
case MsgType.RpcCall: return pluginRpc.forwardCall(msg);
|
|
|
|
case MsgType.Custom: return pluginRpc.forwardMessage(msg);
|
|
|
|
}
|
|
|
|
throw new Error(`Invalid message type for forwardPluginRpc: ${msg.mtype}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reload documents plugins.
|
|
|
|
*/
|
|
|
|
public async reloadPlugins(docSession: DocSession) {
|
|
|
|
// refresh the list plugins found on the system
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
if (!this._docManager.pluginManager || !this.docPluginManager) { return; }
|
2020-07-21 13:20:51 +00:00
|
|
|
await this._docManager.pluginManager.reloadPlugins();
|
|
|
|
const plugins = this._docManager.pluginManager.getPlugins();
|
|
|
|
// reload found plugins
|
|
|
|
await this.docPluginManager.reload(plugins);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Immediately close the document and data engine, to be reloaded from scratch, and cause all
|
|
|
|
* browser clients to reopen it.
|
|
|
|
*/
|
|
|
|
public async reloadDoc(docSession?: DocSession) {
|
2023-04-12 16:18:48 +00:00
|
|
|
this._log.debug(docSession || null, 'ActiveDoc.reloadDoc starting shutdown');
|
2020-07-21 13:20:51 +00:00
|
|
|
return this.shutdown();
|
|
|
|
}
|
|
|
|
|
2021-03-02 21:11:37 +00:00
|
|
|
public isOwner(docSession: OptDocSession): Promise<boolean> {
|
2020-12-14 17:42:09 +00:00
|
|
|
return this._granularAccess.isOwner(docSession);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
2023-02-20 02:51:40 +00:00
|
|
|
* Fork the current document.
|
|
|
|
*
|
|
|
|
* TODO: reconcile the two ways there are now of preparing a fork.
|
2020-07-21 13:20:51 +00:00
|
|
|
*/
|
2021-01-12 15:48:40 +00:00
|
|
|
public async fork(docSession: OptDocSession): Promise<ForkResult> {
|
2024-01-12 17:35:24 +00:00
|
|
|
const dbManager = this._getHomeDbManagerOrFail();
|
2021-01-12 15:48:40 +00:00
|
|
|
const user = getDocSessionUser(docSession);
|
|
|
|
// For now, fork only if user can read everything (or is owner).
|
|
|
|
// TODO: allow forks with partial content.
|
2021-03-25 17:37:09 +00:00
|
|
|
if (!user || !await this.canDownload(docSession)) {
|
2021-01-12 15:48:40 +00:00
|
|
|
throw new ApiError('Insufficient access to document to copy it entirely', 403);
|
2020-09-11 20:27:09 +00:00
|
|
|
}
|
2021-01-12 15:48:40 +00:00
|
|
|
const userId = user.id;
|
|
|
|
const isAnonymous = this._docManager.isAnonymous(userId);
|
2023-02-20 02:51:40 +00:00
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Get fresh document metadata (the cached metadata doesn't include the urlId).
|
2023-02-20 02:51:40 +00:00
|
|
|
let doc: Document | undefined;
|
|
|
|
if (docSession.authorizer) {
|
|
|
|
doc = await docSession.authorizer.getDoc();
|
|
|
|
} else if (docSession.req) {
|
2024-01-12 17:35:24 +00:00
|
|
|
doc = await dbManager.getDoc(docSession.req);
|
2023-02-20 02:51:40 +00:00
|
|
|
}
|
|
|
|
if (!doc) { throw new Error('Document not found'); }
|
|
|
|
|
|
|
|
// Don't allow creating forks of forks (for now).
|
|
|
|
if (doc.trunkId) { throw new ApiError("Cannot fork a document that's already a fork", 400); }
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
const trunkDocId = doc.id;
|
|
|
|
const trunkUrlId = doc.urlId || doc.id;
|
|
|
|
await this.flushDoc(); // Make sure fork won't be too out of date.
|
2021-01-12 15:48:40 +00:00
|
|
|
const forkIds = makeForkIds({userId, isAnonymous, trunkDocId, trunkUrlId});
|
|
|
|
|
|
|
|
// To actually create the fork, we call an endpoint. This is so the fork
|
|
|
|
// can be associated with an arbitrary doc worker, rather than tied to the
|
|
|
|
// same worker as the trunk. We use a Permit for authorization.
|
|
|
|
const permitStore = this._docManager.gristServer.getPermitStore();
|
|
|
|
const permitKey = await permitStore.setPermit({docId: forkIds.docId,
|
|
|
|
otherDocId: this.docName});
|
|
|
|
try {
|
2021-01-27 23:03:30 +00:00
|
|
|
const url = await this._docManager.gristServer.getHomeUrlByDocId(
|
|
|
|
forkIds.docId, `/api/docs/${forkIds.docId}/create-fork`);
|
2021-01-12 15:48:40 +00:00
|
|
|
const resp = await fetch(url, {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({ srcDocId: this.docName }),
|
|
|
|
headers: {
|
2021-01-27 23:03:30 +00:00
|
|
|
'Permit': permitKey,
|
2021-01-12 15:48:40 +00:00
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
});
|
|
|
|
if (resp.status !== 200) {
|
|
|
|
throw new ApiError(resp.statusText, resp.status);
|
|
|
|
}
|
2023-02-20 02:51:40 +00:00
|
|
|
|
|
|
|
await dbManager.forkDoc(userId, doc, forkIds.forkId);
|
2023-04-06 15:10:29 +00:00
|
|
|
|
2023-11-01 13:54:19 +00:00
|
|
|
const isTemplate = doc.type === 'template';
|
2023-04-06 15:10:29 +00:00
|
|
|
this.logTelemetryEvent(docSession, 'documentForked', {
|
2023-06-06 17:08:50 +00:00
|
|
|
limited: {
|
2023-07-04 21:21:34 +00:00
|
|
|
forkIdDigest: forkIds.forkId,
|
|
|
|
forkDocIdDigest: forkIds.docId,
|
|
|
|
trunkIdDigest: doc.trunkId,
|
2023-06-06 17:08:50 +00:00
|
|
|
isTemplate,
|
|
|
|
lastActivity: doc.updatedAt,
|
|
|
|
},
|
2023-04-06 15:10:29 +00:00
|
|
|
});
|
2021-01-12 15:48:40 +00:00
|
|
|
} finally {
|
|
|
|
await permitStore.removePermit(permitKey);
|
|
|
|
}
|
|
|
|
|
|
|
|
return forkIds;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2022-07-19 15:39:49 +00:00
|
|
|
public async getAccessToken(docSession: OptDocSession, options: AccessTokenOptions): Promise<AccessTokenResult> {
|
|
|
|
const tokens = this._docManager.gristServer.getAccessTokens();
|
|
|
|
const userId = getDocSessionUserId(docSession);
|
|
|
|
const docId = this.docName;
|
|
|
|
const access = getDocSessionAccess(docSession);
|
|
|
|
// If we happen to be using a "readOnly" connection, max out at "readOnly"
|
|
|
|
// even if user could do more.
|
|
|
|
if (roles.getStrongestRole('viewers', access) === 'viewers') {
|
|
|
|
options.readOnly = true;
|
|
|
|
}
|
|
|
|
// Return a token that can be used to authorize as the given user.
|
|
|
|
if (!userId) { throw new Error('creating access token requires a user'); }
|
|
|
|
const token = await tokens.sign({
|
|
|
|
readOnly: options.readOnly,
|
|
|
|
userId, // definitely do not want userId overridable by options.
|
|
|
|
docId, // likewise for docId.
|
|
|
|
});
|
|
|
|
const ttlMsecs = tokens.getNominalTTLInMsec();
|
|
|
|
const baseUrl = this._options?.docApiUrl;
|
|
|
|
if (!baseUrl) { throw new Error('cannot create token without URLs'); }
|
|
|
|
return {
|
|
|
|
token,
|
|
|
|
baseUrl,
|
|
|
|
ttlMsecs,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-12-15 04:19:38 +00:00
|
|
|
/**
|
|
|
|
* Check if an ACL formula is valid. If not, will throw an error with an explanation.
|
|
|
|
*/
|
2021-03-10 14:08:46 +00:00
|
|
|
public async checkAclFormula(docSession: DocSession, text: string): Promise<FormulaProperties> {
|
2020-12-15 04:19:38 +00:00
|
|
|
// Checks can leak names of tables and columns.
|
2021-03-10 14:08:46 +00:00
|
|
|
if (await this._granularAccess.hasNuancedAccess(docSession)) { return {}; }
|
2020-12-15 04:19:38 +00:00
|
|
|
await this.waitForInitialization();
|
|
|
|
try {
|
|
|
|
const parsedAclFormula = await this._pyCall('parse_acl_formula', text);
|
|
|
|
compileAclFormula(parsedAclFormula);
|
|
|
|
// TODO We also need to check the validity of attributes, and of tables and columns
|
|
|
|
// mentioned in resources and userAttribute rules.
|
2021-03-10 14:08:46 +00:00
|
|
|
return getFormulaProperties(parsedAclFormula);
|
2020-12-15 04:19:38 +00:00
|
|
|
} catch (e) {
|
|
|
|
e.message = e.message?.replace('[Sandbox] ', '');
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-14 16:10:42 +00:00
|
|
|
/**
|
2022-07-18 11:57:56 +00:00
|
|
|
* Returns the full set of tableIds, with basic metadata for each table. This is intended
|
2021-01-14 16:10:42 +00:00
|
|
|
* for editing ACLs. It is only available to users who can edit ACLs, and lists all resources
|
|
|
|
* regardless of rules that may block access to them.
|
2022-12-05 16:37:48 +00:00
|
|
|
*
|
|
|
|
* Also returns information about resources mentioned in rules that no longer
|
|
|
|
* exist.
|
2021-01-14 16:10:42 +00:00
|
|
|
*/
|
2022-12-05 16:37:48 +00:00
|
|
|
public async getAclResources(docSession: DocSession): Promise<AclResources> {
|
2021-03-25 17:37:09 +00:00
|
|
|
if (!this.docData || !await this._granularAccess.hasAccessRulesPermission(docSession)) {
|
2021-01-14 16:10:42 +00:00
|
|
|
throw new Error('Cannot list ACL resources');
|
|
|
|
}
|
2022-07-18 11:57:56 +00:00
|
|
|
const result: {[tableId: string]: AclTableDescription} = {};
|
2021-12-07 11:21:16 +00:00
|
|
|
const tables = this.docData.getMetaTable('_grist_Tables');
|
2022-07-18 11:57:56 +00:00
|
|
|
const sections = this.docData.getMetaTable('_grist_Views_section');
|
2021-12-07 11:21:16 +00:00
|
|
|
const columns = this.docData.getMetaTable('_grist_Tables_column');
|
2022-07-18 11:57:56 +00:00
|
|
|
for (const table of tables.getRecords()) {
|
|
|
|
const sourceTable = table.summarySourceTable ? tables.getRecord(table.summarySourceTable)! : table;
|
|
|
|
const rawSection = sections.getRecord(sourceTable.rawViewSectionRef)!;
|
|
|
|
result[table.tableId] = {
|
|
|
|
title: rawSection.title || sourceTable.tableId,
|
|
|
|
colIds: ['id'],
|
|
|
|
groupByColLabels: table.summarySourceTable ? [] : null,
|
|
|
|
};
|
|
|
|
}
|
2021-01-14 16:10:42 +00:00
|
|
|
for (const col of columns.getRecords()) {
|
2021-12-07 11:21:16 +00:00
|
|
|
const tableId = tables.getValue(col.parentId, 'tableId')!;
|
2022-07-18 11:57:56 +00:00
|
|
|
result[tableId].colIds.push(col.colId);
|
|
|
|
if (col.summarySourceCol) {
|
|
|
|
const sourceCol = columns.getRecord(col.summarySourceCol)!;
|
|
|
|
result[tableId].groupByColLabels!.push(sourceCol.label);
|
|
|
|
}
|
2021-01-14 16:10:42 +00:00
|
|
|
}
|
2022-12-05 16:37:48 +00:00
|
|
|
const ruleCollection = new ACLRuleCollection();
|
|
|
|
await ruleCollection.update(this.docData, {log});
|
|
|
|
const problems = ruleCollection.findRuleProblems(this.docData);
|
|
|
|
return {tables: result, problems};
|
2021-01-14 16:10:42 +00:00
|
|
|
}
|
|
|
|
|
2021-10-08 14:56:33 +00:00
|
|
|
/**
|
|
|
|
* Get users that are worth proposing to "View As" for access control purposes.
|
|
|
|
* User are drawn from the following sources:
|
|
|
|
* - Users document is shared with.
|
|
|
|
* - Users mentioned in user attribute tables keyed by email address.
|
|
|
|
* - Some predefined example users.
|
|
|
|
*
|
|
|
|
* The users the document is shared with are only available if the
|
|
|
|
* user is an owner of the document (or, in a fork, an owner of the
|
|
|
|
* trunk document). For viewers or editors, only the user calling
|
|
|
|
* the method will be included as users the document is shared with.
|
|
|
|
*
|
|
|
|
* Users mentioned in user attribute tables will be available to any user with
|
|
|
|
* the right to view access rules.
|
|
|
|
*
|
|
|
|
* Example users are always included.
|
|
|
|
*/
|
2023-01-03 10:52:25 +00:00
|
|
|
public async getUsersForViewAs(docSession: OptDocSession): Promise<PermissionDataWithExtraUsers> {
|
2021-10-08 14:56:33 +00:00
|
|
|
// Make sure we have rights to view access rules.
|
2023-05-23 19:17:28 +00:00
|
|
|
if (!await this._granularAccess.hasAccessRulesPermission(docSession)) {
|
2021-10-08 14:56:33 +00:00
|
|
|
throw new Error('Cannot list ACL users');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Prepare a stub for the collected results.
|
|
|
|
const result: PermissionDataWithExtraUsers = {
|
|
|
|
users: [],
|
|
|
|
attributeTableUsers: [],
|
|
|
|
exampleUsers: [],
|
|
|
|
};
|
|
|
|
const isShared = new Set<string>();
|
|
|
|
|
|
|
|
// Collect users the document is shared with.
|
|
|
|
const userId = getDocSessionUserId(docSession);
|
|
|
|
if (!userId) { throw new Error('Cannot determine user'); }
|
2023-05-23 19:17:28 +00:00
|
|
|
const db = this.getHomeDbManager();
|
|
|
|
if (db) {
|
|
|
|
const access = db.unwrapQueryResult(
|
|
|
|
await db.getDocAccess({userId, urlId: this.docName}, {
|
|
|
|
flatten: true, excludeUsersWithoutAccess: true,
|
|
|
|
}));
|
|
|
|
result.users = access.users;
|
|
|
|
result.users.forEach(user => isShared.add(normalizeEmail(user.email)));
|
|
|
|
}
|
2021-10-08 14:56:33 +00:00
|
|
|
|
|
|
|
// Collect users from user attribute tables. Omit duplicates with users the document is
|
|
|
|
// shared with.
|
|
|
|
const usersFromUserAttributes = await this._granularAccess.collectViewAsUsersFromUserAttributeTables();
|
|
|
|
for (const user of usersFromUserAttributes) {
|
|
|
|
if (!user.email) { continue; }
|
|
|
|
const email = normalizeEmail(user.email);
|
|
|
|
if (!isShared.has(email)) {
|
|
|
|
result.attributeTableUsers.push({email: user.email, name: user.name || '',
|
|
|
|
id: 0, access: user.access === undefined ? 'editors' : user.access});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add some example users.
|
|
|
|
result.exampleUsers = this._granularAccess.getExampleViewAsUsers();
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
public getGristDocAPI(): GristDocAPI {
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
if (!this.docPluginManager) { throw new Error('no plugin manager available'); }
|
2020-07-21 13:20:51 +00:00
|
|
|
return this.docPluginManager.gristDocAPI;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get recent actions in ActionGroup format with summaries included.
|
|
|
|
public async getActionSummaries(docSession: DocSession): Promise<ActionGroup[]> {
|
2020-09-02 18:17:17 +00:00
|
|
|
return this.getRecentActions(docSession, true);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Applies normal actions to the data engine while processing onDemand actions separately.
|
2020-12-07 21:15:58 +00:00
|
|
|
* Should only be called by a Sharing object, with this._modificationLock held, since the
|
|
|
|
* actions may need to be rolled back if final access control checks fail.
|
2020-07-21 13:20:51 +00:00
|
|
|
*/
|
2021-07-15 00:45:53 +00:00
|
|
|
public async applyActionsToDataEngine(
|
|
|
|
docSession: OptDocSession|null,
|
|
|
|
userActions: UserAction[]
|
|
|
|
): Promise<SandboxActionBundle> {
|
2023-05-08 22:06:24 +00:00
|
|
|
const [normalActions, onDemandActions] = this._onDemandActions.splitByStorage(userActions);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
let sandboxActionBundle: SandboxActionBundle;
|
|
|
|
if (normalActions.length > 0) {
|
|
|
|
// For all but the special 'Calculate' action, we wait for full initialization.
|
|
|
|
if (normalActions[0][0] !== 'Calculate') {
|
|
|
|
await this.waitForInitialization();
|
|
|
|
}
|
2021-07-15 00:45:53 +00:00
|
|
|
const user = docSession ? await this._granularAccess.getCachedUser(docSession) : undefined;
|
|
|
|
sandboxActionBundle = await this._rawPyCall('apply_user_actions', normalActions, user?.toJSON());
|
2022-06-17 18:49:18 +00:00
|
|
|
const {requests} = sandboxActionBundle;
|
|
|
|
if (requests) {
|
|
|
|
this._requests.handleRequestsBatchFromUserActions(requests).catch(e => console.error(e));
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
await this._reportDataEngineMemory();
|
|
|
|
} else {
|
|
|
|
// Create default SandboxActionBundle to use if the data engine is not called.
|
|
|
|
sandboxActionBundle = createEmptySandboxActionBundle();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (onDemandActions.length > 0) {
|
|
|
|
const allIndex = findOrAddAllEnvelope(sandboxActionBundle.envelopes);
|
|
|
|
await this.docStorage.execTransaction(async () => {
|
|
|
|
for (const action of onDemandActions) {
|
|
|
|
const {stored, undo, retValues} = await this._onDemandActions.processUserAction(action);
|
|
|
|
// Note: onDemand stored/undo actions are arbitrarily processed/added after normal actions
|
|
|
|
// and do not support access control.
|
|
|
|
sandboxActionBundle.stored.push(...stored.map(a => [allIndex, a] as [number, DocAction]));
|
2021-05-12 15:04:37 +00:00
|
|
|
sandboxActionBundle.direct.push(...stored.map(a => [allIndex, true] as [number, boolean]));
|
2020-07-21 13:20:51 +00:00
|
|
|
sandboxActionBundle.undo.push(...undo.map(a => [allIndex, a] as [number, DocAction]));
|
|
|
|
sandboxActionBundle.retValues.push(retValues);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return sandboxActionBundle;
|
|
|
|
}
|
|
|
|
|
2022-04-07 12:34:50 +00:00
|
|
|
/**
|
|
|
|
* Check which attachments in the _grist_Attachments metadata are actually used,
|
|
|
|
* i.e. referenced by some cell in an Attachments type column.
|
|
|
|
* Set timeDeleted to the current time on newly unused attachments,
|
|
|
|
* 'soft deleting' them so that they get cleaned up automatically from _gristsys_Files after enough time has passed.
|
|
|
|
* Set timeDeleted to null on used attachments that were previously soft deleted,
|
|
|
|
* so that undo can 'undelete' attachments.
|
2022-04-14 12:19:36 +00:00
|
|
|
* Returns true if any changes were made, i.e. some row(s) of _grist_Attachments were updated.
|
2022-04-07 12:34:50 +00:00
|
|
|
*/
|
2022-05-03 05:20:31 +00:00
|
|
|
public async updateUsedAttachmentsIfNeeded() {
|
2022-04-07 12:34:50 +00:00
|
|
|
const changes = await this.docStorage.scanAttachmentsForUsageChanges();
|
|
|
|
if (!changes.length) {
|
2022-04-14 12:19:36 +00:00
|
|
|
return false;
|
2022-04-07 12:34:50 +00:00
|
|
|
}
|
|
|
|
const rowIds = changes.map(r => r.id);
|
|
|
|
const now = Date.now() / 1000;
|
|
|
|
const timeDeleted = changes.map(r => r.used ? null : now);
|
|
|
|
const action: BulkUpdateRecord = ["BulkUpdateRecord", "_grist_Attachments", rowIds, {timeDeleted}];
|
|
|
|
// Don't use applyUserActions which may block the update action in delete-only mode
|
|
|
|
await this._applyUserActions(makeExceptionalDocSession('system'), [action]);
|
2022-04-14 12:19:36 +00:00
|
|
|
return true;
|
2022-04-07 12:34:50 +00:00
|
|
|
}
|
|
|
|
|
2022-04-12 14:33:48 +00:00
|
|
|
/**
|
|
|
|
* Delete unused attachments from _grist_Attachments and gristsys_Files.
|
|
|
|
* @param expiredOnly: if true, only delete attachments that were soft-deleted sufficiently long ago.
|
2022-05-16 17:41:12 +00:00
|
|
|
* @param options.syncUsageToDatabase: if true, schedule an update to the usage column of the docs table, if
|
|
|
|
* any unused attachments were soft-deleted. defaults to true.
|
2022-06-06 16:21:26 +00:00
|
|
|
* @param options.broadcastUsageToClients: if true, broadcast updated doc usage to all clients, if
|
|
|
|
* any unused attachments were soft-deleted. defaults to true.
|
2022-04-12 14:33:48 +00:00
|
|
|
*/
|
2022-06-06 16:21:26 +00:00
|
|
|
public async removeUnusedAttachments(expiredOnly: boolean, options?: UpdateUsageOptions) {
|
2022-05-03 05:20:31 +00:00
|
|
|
const hadChanges = await this.updateUsedAttachmentsIfNeeded();
|
2022-06-06 16:21:26 +00:00
|
|
|
if (hadChanges) {
|
|
|
|
await this._updateAttachmentsSize(options);
|
|
|
|
}
|
2022-04-12 14:33:48 +00:00
|
|
|
const rowIds = await this.docStorage.getSoftDeletedAttachmentIds(expiredOnly);
|
|
|
|
if (rowIds.length) {
|
|
|
|
const action: BulkRemoveRecord = ["BulkRemoveRecord", "_grist_Attachments", rowIds];
|
|
|
|
await this.applyUserActions(makeExceptionalDocSession('system'), [action]);
|
|
|
|
}
|
2023-01-18 17:19:23 +00:00
|
|
|
try {
|
|
|
|
await this.docStorage.removeUnusedAttachments();
|
|
|
|
} catch (e) {
|
|
|
|
// If document doesn't have _gristsys_Files, don't worry about it;
|
|
|
|
// if this is an error it will have already been reported, and the
|
|
|
|
// document can be in this state when updating initial SQL code after
|
|
|
|
// a schema change.
|
|
|
|
if (!String(e).match(/no such table: _gristsys_Files/)) {
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
2022-04-12 14:33:48 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Needed for test/server/migrations.js tests
|
|
|
|
public async testGetVersionFromDataEngine() {
|
2020-12-07 21:15:58 +00:00
|
|
|
return this._pyCall('get_version');
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Needed for test/server/lib/HostedStorageManager.ts tests
|
|
|
|
public async testKeepOpen() {
|
|
|
|
this._inactivityTimer.ping();
|
|
|
|
}
|
|
|
|
|
2022-11-15 15:58:25 +00:00
|
|
|
public async getSnapshots(docSession: OptDocSession, skipMetadataCache?: boolean): Promise<DocSnapshots> {
|
|
|
|
if (await this._granularAccess.hasNuancedAccess(docSession)) {
|
|
|
|
throw new Error('cannot confirm access to snapshots');
|
|
|
|
}
|
2020-12-18 17:37:16 +00:00
|
|
|
return this._docManager.storageManager.getSnapshots(this.docName, skipMetadataCache);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async removeSnapshots(docSession: OptDocSession, snapshotIds: string[]): Promise<void> {
|
2021-03-02 21:11:37 +00:00
|
|
|
if (!await this.isOwner(docSession)) {
|
2020-12-18 17:37:16 +00:00
|
|
|
throw new Error('cannot remove snapshots, access denied');
|
|
|
|
}
|
|
|
|
return this._docManager.storageManager.removeSnapshots(this.docName, snapshotIds);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async deleteActions(docSession: OptDocSession, keepN: number): Promise<void> {
|
2021-03-02 21:11:37 +00:00
|
|
|
if (!await this.isOwner(docSession)) {
|
2020-12-18 17:37:16 +00:00
|
|
|
throw new Error('cannot delete actions, access denied');
|
|
|
|
}
|
2021-01-14 16:10:42 +00:00
|
|
|
await this._actionHistory.deleteActions(keepN);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Make sure the current version of the document has been pushed to persistent
|
|
|
|
* storage.
|
|
|
|
*/
|
|
|
|
public async flushDoc(): Promise<void> {
|
|
|
|
return this._docManager.storageManager.flushDoc(this.docName);
|
|
|
|
}
|
|
|
|
|
|
|
|
public makeAccessId(userId: number|null): string|null {
|
|
|
|
return this._docManager.makeAccessId(userId);
|
|
|
|
}
|
|
|
|
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
/**
|
|
|
|
* Apply actions that have already occurred in the data engine to the
|
|
|
|
* database also.
|
|
|
|
*/
|
|
|
|
public async applyStoredActionsToDocStorage(docActions: DocAction[]): Promise<void> {
|
|
|
|
// When "gristifying" an sqlite database, we may take create tables and
|
|
|
|
// columns in the data engine that already exist in the sqlite database.
|
|
|
|
// During that process, _onlyAllowMetaDataActionsOnDb will be turned on,
|
|
|
|
// and we silently swallow any non-metadata actions.
|
|
|
|
if (this._onlyAllowMetaDataActionsOnDb) {
|
|
|
|
docActions = docActions.filter(a => getTableId(a).startsWith('_grist'));
|
|
|
|
}
|
|
|
|
await this.docStorage.applyStoredActions(docActions);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set a flag that controls whether user data can be changed in the database,
|
|
|
|
// or only grist-managed tables (those whose names start with _grist)
|
|
|
|
public onlyAllowMetaDataActionsOnDb(flag: boolean) {
|
|
|
|
this._onlyAllowMetaDataActionsOnDb = flag;
|
|
|
|
}
|
|
|
|
|
2020-12-07 21:15:58 +00:00
|
|
|
/**
|
|
|
|
* Called by Sharing manager when working on modifying the document.
|
|
|
|
* Called when DocActions have been produced from UserActions, but
|
2021-03-01 16:51:30 +00:00
|
|
|
* before those DocActions have been applied to the DB. GranularAccessBundle
|
|
|
|
* methods can confirm that those DocActions are legal according to any
|
|
|
|
* granular access rules.
|
2020-12-07 21:15:58 +00:00
|
|
|
*/
|
2021-03-01 16:51:30 +00:00
|
|
|
public getGranularAccessForBundle(docSession: OptDocSession, docActions: DocAction[], undo: DocAction[],
|
2022-11-15 14:37:48 +00:00
|
|
|
userActions: UserAction[], isDirect: boolean[],
|
|
|
|
options: ApplyUAOptions|null): GranularAccessForBundle {
|
|
|
|
this._granularAccess.getGranularAccessForBundle(docSession, docActions, undo, userActions, isDirect, options);
|
2021-03-01 16:51:30 +00:00
|
|
|
return this._granularAccess;
|
2020-09-02 18:17:17 +00:00
|
|
|
}
|
|
|
|
|
2022-08-03 07:18:21 +00:00
|
|
|
public async updateRowCount(rowCount: RowCounts, docSession: OptDocSession | null) {
|
2022-06-06 16:21:26 +00:00
|
|
|
// Up-to-date row counts are included in every DocUserAction, so we can skip broadcasting here.
|
|
|
|
await this._updateDocUsage({rowCount}, {broadcastUsageToClients: false});
|
2022-08-03 07:18:21 +00:00
|
|
|
log.rawInfo('Sandbox row count', {...this.getLogMeta(docSession), rowCount: rowCount.total});
|
2022-03-30 11:45:37 +00:00
|
|
|
await this._checkDataLimitRatio();
|
|
|
|
|
2022-06-06 16:21:26 +00:00
|
|
|
// Calculating data size is potentially expensive, so skip calculating it unless the
|
|
|
|
// user is currently being warned specifically about approaching or exceeding the data
|
|
|
|
// size limit, but not the row count limit; we don't need to warn about both limits at
|
|
|
|
// the same time.
|
2022-03-30 11:45:37 +00:00
|
|
|
if (
|
|
|
|
this.dataSizeLimitRatio > APPROACHING_LIMIT_RATIO && this.rowLimitRatio <= APPROACHING_LIMIT_RATIO ||
|
|
|
|
this.dataSizeLimitRatio > 1.0 && this.rowLimitRatio <= 1.0
|
|
|
|
) {
|
2022-06-06 16:21:26 +00:00
|
|
|
await this._checkDataSizeLimitRatio(docSession);
|
2022-03-30 11:45:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-30 12:04:27 +00:00
|
|
|
/**
|
|
|
|
* Clears all outgoing webhook requests queued for this document.
|
|
|
|
*/
|
|
|
|
public async clearWebhookQueue() {
|
|
|
|
await this._triggers.clearWebhookQueue();
|
|
|
|
}
|
|
|
|
|
2023-07-18 07:24:10 +00:00
|
|
|
public async clearSingleWebhookQueue(webhookId: string) {
|
|
|
|
await this._triggers.clearSingleWebhookQueue(webhookId);
|
|
|
|
}
|
|
|
|
|
(core) Adding /webhooks endpoint
Summary:
- New /webhooks event that lists all webhooks in a document (available for owners),
- Monitoring webhooks usage and saving it in memory or Redis,
- Loosening _usubscribe API endpoint, so that the information returned from the /webhook endpoint is enough to unsubscribe,
- Owners can remove webhook without the unsubscribe key.
The endpoint lists all webhooks that are registered in a document, not just webhooks from a single table.
There are two status fields. First for the webhook, second for the last request attempt.
Webhook can have 5 statuses: 'idle', 'sending', 'retrying', 'postponed', 'error', which roughly describes what the
sendLoop is currently doing. The 'error' status describes a situation when all request attempts failed and the queue needs
to be drained, so some requests were dropped.
The last request status can only be: 'success', 'failure' or 'rejected'. Rejected means that the last batch was dropped because the
queue was too long.
Test Plan: New and updated tests
Reviewers: paulfitz
Reviewed By: paulfitz
Differential Revision: https://phab.getgrist.com/D3727
2022-12-13 11:47:50 +00:00
|
|
|
/**
|
|
|
|
* Returns the list of outgoing webhook for a table in this document.
|
|
|
|
*/
|
|
|
|
public async webhooksSummary() {
|
|
|
|
return this._triggers.summary();
|
|
|
|
}
|
|
|
|
|
2023-05-08 22:06:24 +00:00
|
|
|
/**
|
|
|
|
* Send a message to clients connected to the document that something
|
2023-07-18 07:24:10 +00:00
|
|
|
* webhook-related has happened (a change in configuration, a delivery,
|
|
|
|
* or an error). It passes information about the type of event (currently data being updated in some way
|
|
|
|
* or an OverflowError, i.e., too many events waiting to be sent). More data may be added when necessary.
|
2023-05-08 22:06:24 +00:00
|
|
|
*/
|
2023-07-18 07:24:10 +00:00
|
|
|
public async sendWebhookNotification(type: WebhookMessageType = WebhookMessageType.Update) {
|
2023-05-08 22:06:24 +00:00
|
|
|
await this.docClients.broadcastDocMessage(null, 'docChatter', {
|
2023-07-18 07:24:10 +00:00
|
|
|
webhooks: {type},
|
2023-05-08 22:06:24 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-04-06 15:10:29 +00:00
|
|
|
public logTelemetryEvent(
|
|
|
|
docSession: OptDocSession | null,
|
2023-06-06 17:08:50 +00:00
|
|
|
event: TelemetryEvent,
|
|
|
|
metadata?: TelemetryMetadataByLevel
|
2023-04-06 15:10:29 +00:00
|
|
|
) {
|
2023-11-01 13:54:19 +00:00
|
|
|
this._docManager.gristServer.getTelemetry().logEvent(docSession, event, merge(
|
2023-06-06 17:08:50 +00:00
|
|
|
this._getTelemetryMeta(docSession),
|
|
|
|
metadata,
|
2023-11-01 13:54:19 +00:00
|
|
|
));
|
2023-04-06 15:10:29 +00:00
|
|
|
}
|
|
|
|
|
(core) notify home db of shares when copying/forking/uploading docs
Summary:
The first time a worker opens a document, it will now check if it has any shares the home db needs to be aware of. If so, they will be added. This is important for documents uploaded/copied/forked/replaced, so that their shares work out of the box.
In future, may want some UI to give user control of whether shares are activated after upload/copy/fork/replace.
It seems tricky currently to know if a document is being opened for the first time. As a proxy, I check whether usage information has been calculated and saved to the db, since I can determine that without adding another db query. It is safe to synchronize shares more than necessary.
This leaves two gaps:
* If a document is created/uploaded/copied/forked/replaced and no attempt is made to access it prior to using a share, then that share won't actually be available. Not a problem currently I think, since how would a user have determined the share key. But in future it would be good to also do a sync after creation/upload/copy/fork/replacement/...
* On document replacement, usage info is reset but not absolutely immediately. So in principle shares could fail to be created on first load of the replacement. Usage info reset could be tweaked to give a guarantee here, but also fixing the first point would resolve this second point too.
Test Plan: copy test added
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D4165
2024-01-12 22:05:13 +00:00
|
|
|
/**
|
|
|
|
* Make sure the shares listed for the doc in the home db and the
|
|
|
|
* shares listed within the doc itself are in sync. If skipIfNoShares
|
|
|
|
* is set, we skip checking the home db if there are no shares listed
|
|
|
|
* within the doc, as a small optimization.
|
|
|
|
*/
|
|
|
|
public async syncShares(docSession: OptDocSession, options: {
|
|
|
|
skipIfNoShares?: boolean,
|
|
|
|
} = {}) {
|
(core) add initial support for special shares
Summary:
This gives a mechanism for controlling access control within a document that is distinct from (though implemented with the same machinery as) granular access rules.
It was hard to find a good way to insert this that didn't dissolve in a soup of complications, so here's what I went with:
* When reading rules, if there are shares, extra rules are added.
* If there are shares, all rules are made conditional on a "ShareRef" user property.
* "ShareRef" is null when a doc is accessed in normal way, and the row id of a share when accessed via a share.
There's no UI for controlling shares (George is working on it for forms), but you can do it by editing a `_grist_Shares` table in a document. Suppose you make a fresh document with a single page/table/widget, then to create an empty share you can do:
```
gristDocPageModel.gristDoc.get().docData.sendAction(['AddRecord', '_grist_Shares', null, {linkId: 'xyz', options: '{"publish": true}'}])
```
If you look at the home db now there should be something in the `shares` table:
```
$ sqlite3 -table landing.db "select * from shares"
+----+------------------------+------------------------+--------------+---------+
| id | key | doc_id | link_id | options |
+----+------------------------+------------------------+--------------+---------+
| 1 | gSL4g38PsyautLHnjmXh2K | 4qYuace1xP2CTcPunFdtan | xyz | ... |
+----+------------------------+------------------------+--------------+---------+
```
If you take the key from that (gSL4g38PsyautLHnjmXh2K in this case) and replace the document's urlId in its URL with `s.<key>` (in this case `s.gSL4g38PsyautLHnjmXh2K` then you can use the regular document landing page (it will be quite blank initially) or API endpoint via the share.
E.g. for me `http://localhost:8080/o/docs/s0gSL4g38PsyautLHnjmXh2K/share-inter-3` accesses the doc.
To actually share some material - useful commands:
```
gristDocPageModel.gristDoc.get().docData.getMetaTable('_grist_Views_section').getRecords()
gristDocPageModel.gristDoc.get().docData.sendAction(['UpdateRecord', '_grist_Views_section', 1, {shareOptions: '{"publish": true, "form": true}'}])
gristDocPageModel.gristDoc.get().docData.getMetaTable('_grist_Pages').getRecords()
gristDocPageModel.gristDoc.get().docData.sendAction(['UpdateRecord', '_grist_Pages', 1, {shareRef: 1}])
```
For a share to be effective, at least one page needs to have its shareRef set to the rowId of the share, and at least one widget on one of those pages needs to have its shareOptions set to {"publish": "true", "form": "true"} (meaning turn on sharing, and include form sharing), and the share itself needs {"publish": true} on its options.
I think special shares are kind of incompatible with public sharing, since by their nature (allowing access to all endpoints) they easily expose the docId, and changing that would be hard.
Test Plan: tests added
Reviewers: dsagal, georgegevoian
Reviewed By: dsagal, georgegevoian
Subscribers: jarek, dsagal
Differential Revision: https://phab.getgrist.com/D4144
2024-01-03 16:53:20 +00:00
|
|
|
const metaTables = await this.fetchMetaTables(docSession);
|
|
|
|
const shares = metaTables['_grist_Shares'];
|
|
|
|
const ids = shares[2];
|
|
|
|
const vals = shares[3];
|
|
|
|
const goodShares = ids.map((id, idx) => {
|
|
|
|
return {
|
|
|
|
id,
|
|
|
|
linkId: String(vals['linkId'][idx]),
|
|
|
|
options: String(vals['options'][idx]),
|
|
|
|
};
|
|
|
|
});
|
(core) notify home db of shares when copying/forking/uploading docs
Summary:
The first time a worker opens a document, it will now check if it has any shares the home db needs to be aware of. If so, they will be added. This is important for documents uploaded/copied/forked/replaced, so that their shares work out of the box.
In future, may want some UI to give user control of whether shares are activated after upload/copy/fork/replace.
It seems tricky currently to know if a document is being opened for the first time. As a proxy, I check whether usage information has been calculated and saved to the db, since I can determine that without adding another db query. It is safe to synchronize shares more than necessary.
This leaves two gaps:
* If a document is created/uploaded/copied/forked/replaced and no attempt is made to access it prior to using a share, then that share won't actually be available. Not a problem currently I think, since how would a user have determined the share key. But in future it would be good to also do a sync after creation/upload/copy/fork/replacement/...
* On document replacement, usage info is reset but not absolutely immediately. So in principle shares could fail to be created on first load of the replacement. Usage info reset could be tweaked to give a guarantee here, but also fixing the first point would resolve this second point too.
Test Plan: copy test added
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D4165
2024-01-12 22:05:13 +00:00
|
|
|
if (goodShares.length > 0 || !options.skipIfNoShares) {
|
|
|
|
await this._getHomeDbManagerOrFail().syncShares(this.docName, goodShares);
|
|
|
|
}
|
(core) add initial support for special shares
Summary:
This gives a mechanism for controlling access control within a document that is distinct from (though implemented with the same machinery as) granular access rules.
It was hard to find a good way to insert this that didn't dissolve in a soup of complications, so here's what I went with:
* When reading rules, if there are shares, extra rules are added.
* If there are shares, all rules are made conditional on a "ShareRef" user property.
* "ShareRef" is null when a doc is accessed in normal way, and the row id of a share when accessed via a share.
There's no UI for controlling shares (George is working on it for forms), but you can do it by editing a `_grist_Shares` table in a document. Suppose you make a fresh document with a single page/table/widget, then to create an empty share you can do:
```
gristDocPageModel.gristDoc.get().docData.sendAction(['AddRecord', '_grist_Shares', null, {linkId: 'xyz', options: '{"publish": true}'}])
```
If you look at the home db now there should be something in the `shares` table:
```
$ sqlite3 -table landing.db "select * from shares"
+----+------------------------+------------------------+--------------+---------+
| id | key | doc_id | link_id | options |
+----+------------------------+------------------------+--------------+---------+
| 1 | gSL4g38PsyautLHnjmXh2K | 4qYuace1xP2CTcPunFdtan | xyz | ... |
+----+------------------------+------------------------+--------------+---------+
```
If you take the key from that (gSL4g38PsyautLHnjmXh2K in this case) and replace the document's urlId in its URL with `s.<key>` (in this case `s.gSL4g38PsyautLHnjmXh2K` then you can use the regular document landing page (it will be quite blank initially) or API endpoint via the share.
E.g. for me `http://localhost:8080/o/docs/s0gSL4g38PsyautLHnjmXh2K/share-inter-3` accesses the doc.
To actually share some material - useful commands:
```
gristDocPageModel.gristDoc.get().docData.getMetaTable('_grist_Views_section').getRecords()
gristDocPageModel.gristDoc.get().docData.sendAction(['UpdateRecord', '_grist_Views_section', 1, {shareOptions: '{"publish": true, "form": true}'}])
gristDocPageModel.gristDoc.get().docData.getMetaTable('_grist_Pages').getRecords()
gristDocPageModel.gristDoc.get().docData.sendAction(['UpdateRecord', '_grist_Pages', 1, {shareRef: 1}])
```
For a share to be effective, at least one page needs to have its shareRef set to the rowId of the share, and at least one widget on one of those pages needs to have its shareOptions set to {"publish": "true", "form": "true"} (meaning turn on sharing, and include form sharing), and the share itself needs {"publish": true} on its options.
I think special shares are kind of incompatible with public sharing, since by their nature (allowing access to all endpoints) they easily expose the docId, and changing that would be hard.
Test Plan: tests added
Reviewers: dsagal, georgegevoian
Reviewed By: dsagal, georgegevoian
Subscribers: jarek, dsagal
Differential Revision: https://phab.getgrist.com/D4144
2024-01-03 16:53:20 +00:00
|
|
|
return goodShares;
|
|
|
|
}
|
|
|
|
|
2024-01-12 17:35:24 +00:00
|
|
|
public async getShare(_docSession: OptDocSession, linkId: string): Promise<Share|null> {
|
|
|
|
return await this._getHomeDbManagerOrFail().getShareByLinkId(this.docName, linkId);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Loads an open document from DocStorage. Returns a list of the tables it contains.
|
|
|
|
*/
|
(core) Log statistics about table sizes
Summary:
Record numbers of rows, columns, cells, and bytes of marshalled data for most calls to table_data_from_db
Export new function get_table_stats in the sandbox, which gives the raw numbers and totals.
Get and log these stats in ActiveDoc right after loading tables, before Calculate, so they are logged even in case of errors.
Tweak logging about number of tables, especially number of on-demand tables, to not only show in debug logging.
Test Plan: Updated doc regression tests, that shows what the data looks like nicely.
Reviewers: dsagal, paulfitz
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D3081
2021-10-21 13:03:37 +00:00
|
|
|
protected async _loadOpenDoc(docSession: OptDocSession): Promise<string[][]> {
|
2021-10-01 13:45:27 +00:00
|
|
|
// Check the schema version of document and sandbox, and migrate if the sandbox is newer.
|
|
|
|
const schemaVersion = SCHEMA_VERSION;
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
// Migrate the document if needed.
|
2021-10-01 13:45:27 +00:00
|
|
|
const docInfo = await this._tableMetadataLoader.fetchBulkColValuesWithoutIds('_grist_DocInfo');
|
|
|
|
const versionCol = docInfo.schemaVersion;
|
|
|
|
const docSchemaVersion = (versionCol && versionCol.length === 1 ? versionCol[0] : 0) as number;
|
2020-07-21 13:20:51 +00:00
|
|
|
if (docSchemaVersion < schemaVersion) {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "Doc needs migration from v%s to v%s", docSchemaVersion, schemaVersion);
|
2020-10-30 16:53:23 +00:00
|
|
|
await this._beforeMigration(docSession, 'schema', docSchemaVersion, schemaVersion);
|
|
|
|
let success: boolean = false;
|
|
|
|
try {
|
2023-05-23 19:03:50 +00:00
|
|
|
await this._withDataEngine(() => this._migrate(docSession), {
|
|
|
|
shutdownAfter: this._isSnapshot,
|
|
|
|
});
|
2020-10-30 16:53:23 +00:00
|
|
|
success = true;
|
|
|
|
} finally {
|
|
|
|
await this._afterMigration(docSession, 'schema', schemaVersion, success);
|
2021-10-01 13:45:27 +00:00
|
|
|
await this._tableMetadataLoader.clean(); // _grist_DocInfo may have changed.
|
2020-10-30 16:53:23 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
} else if (docSchemaVersion > schemaVersion) {
|
|
|
|
// We do NOT attempt to down-migrate in this case. Migration code cannot down-migrate
|
|
|
|
// directly (since it doesn't know anything about newer documents). We could revert the
|
|
|
|
// migration action, but that requires merging and still may not be safe. For now, doing
|
|
|
|
// nothing seems best, as long as we follow the recommendations in migrations.py (never
|
|
|
|
// remove/modify/rename metadata tables or columns, or change their meaning).
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.warn(docSession, "Doc is newer (v%s) than this version of Grist (v%s); " +
|
2020-07-21 13:20:51 +00:00
|
|
|
"proceeding with fingers crossed", docSchemaVersion, schemaVersion);
|
|
|
|
}
|
|
|
|
|
2023-05-23 19:03:50 +00:00
|
|
|
if (!this._isSnapshot) {
|
|
|
|
this._tableMetadataLoader.startStreamingToEngine();
|
|
|
|
}
|
|
|
|
|
2021-10-01 13:45:27 +00:00
|
|
|
// Start loading the initial meta tables which determine the document schema.
|
|
|
|
this._tableMetadataLoader.startFetchingTable('_grist_Tables');
|
|
|
|
this._tableMetadataLoader.startFetchingTable('_grist_Tables_column');
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2021-10-01 13:45:27 +00:00
|
|
|
// Get names of remaining tables.
|
|
|
|
const tablesParsed = await this._tableMetadataLoader.fetchBulkColValuesWithoutIds('_grist_Tables');
|
|
|
|
const tableNames = (tablesParsed.tableId as string[])
|
|
|
|
.concat(Object.keys(schema))
|
|
|
|
.filter(tableId => tableId !== '_grist_Tables' && tableId !== '_grist_Tables_column')
|
|
|
|
.sort();
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
// Figure out which tables are on-demand.
|
|
|
|
const onDemandMap = zipObject(tablesParsed.tableId as string[], tablesParsed.onDemand);
|
2022-05-18 16:05:37 +00:00
|
|
|
const onDemandNames = remove(tableNames, (t) => (onDemandMap[t] ||
|
|
|
|
(this._recoveryMode && !t.startsWith('_grist_'))));
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "Loading %s normal tables, skipping %s on-demand tables",
|
(core) Log statistics about table sizes
Summary:
Record numbers of rows, columns, cells, and bytes of marshalled data for most calls to table_data_from_db
Export new function get_table_stats in the sandbox, which gives the raw numbers and totals.
Get and log these stats in ActiveDoc right after loading tables, before Calculate, so they are logged even in case of errors.
Tweak logging about number of tables, especially number of on-demand tables, to not only show in debug logging.
Test Plan: Updated doc regression tests, that shows what the data looks like nicely.
Reviewers: dsagal, paulfitz
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D3081
2021-10-21 13:03:37 +00:00
|
|
|
tableNames.length, onDemandNames.length);
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "Normal tables: %s", tableNames.join(", "));
|
|
|
|
this._log.debug(docSession, "On-demand tables: %s", onDemandNames.join(", "));
|
2020-07-21 13:20:51 +00:00
|
|
|
|
(core) Log statistics about table sizes
Summary:
Record numbers of rows, columns, cells, and bytes of marshalled data for most calls to table_data_from_db
Export new function get_table_stats in the sandbox, which gives the raw numbers and totals.
Get and log these stats in ActiveDoc right after loading tables, before Calculate, so they are logged even in case of errors.
Tweak logging about number of tables, especially number of on-demand tables, to not only show in debug logging.
Test Plan: Updated doc regression tests, that shows what the data looks like nicely.
Reviewers: dsagal, paulfitz
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D3081
2021-10-21 13:03:37 +00:00
|
|
|
return [tableNames, onDemandNames];
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Applies an array of user actions to the sandbox and broadcasts the results to doc's clients.
|
|
|
|
*
|
|
|
|
* @private
|
|
|
|
* @param {Object} client - The client originating this action. May be null.
|
|
|
|
* @param {Array} actions - The user actions to apply.
|
|
|
|
* @param {String} options.desc - Description of the action which overrides the default client
|
|
|
|
* description if provided. Should be used to describe bundled actions.
|
|
|
|
* @param {Int} options.otherId - Action number for the original useraction to which this undo/redo
|
|
|
|
* action applies.
|
|
|
|
* @param {Boolean} options.linkId - ActionNumber of the previous action in an undo/redo bundle.
|
|
|
|
* @returns {Promise} Promise that's resolved when all actions are applied successfully to {
|
|
|
|
* actionNum: number of the action that got recorded
|
|
|
|
* retValues: array of return values, one for each of the passed-in user actions.
|
|
|
|
* isModification: true if document was changed by one or more actions.
|
|
|
|
* }
|
|
|
|
*/
|
2020-11-02 15:48:47 +00:00
|
|
|
@ActiveDoc.keepDocOpen
|
2020-09-02 18:17:17 +00:00
|
|
|
protected async _applyUserActions(docSession: OptDocSession, actions: UserAction[],
|
2022-11-15 14:37:48 +00:00
|
|
|
options: ApplyUAExtendedOptions = {}): Promise<ApplyUAResult> {
|
2020-09-11 20:27:09 +00:00
|
|
|
|
2020-09-02 18:17:17 +00:00
|
|
|
const client = docSession.client;
|
2021-12-21 05:40:46 +00:00
|
|
|
this._log.debug(docSession, "_applyUserActions(%s, %s)%s", client, shortDesc(actions),
|
|
|
|
options.parseStrings ? ' (will parse)' : '');
|
2020-07-21 13:20:51 +00:00
|
|
|
this._inactivityTimer.ping(); // The doc is in active use; ping it to stay open longer.
|
|
|
|
|
2021-12-16 13:45:05 +00:00
|
|
|
if (options.parseStrings) {
|
|
|
|
actions = actions.map(ua => parseUserAction(ua, this.docData!));
|
|
|
|
}
|
|
|
|
|
2021-06-09 19:31:59 +00:00
|
|
|
if (options?.bestEffort) {
|
2022-11-15 14:37:48 +00:00
|
|
|
actions = await this._granularAccess.prefilterUserActions(docSession, actions, options);
|
2021-06-09 19:31:59 +00:00
|
|
|
}
|
2022-09-27 17:01:34 +00:00
|
|
|
await this._granularAccess.checkUserActions(docSession, actions);
|
2021-02-15 21:36:33 +00:00
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Create the UserActionBundle.
|
|
|
|
const action: UserActionBundle = {
|
2021-10-01 13:45:27 +00:00
|
|
|
info: this._makeInfo(docSession, options),
|
2022-11-15 14:37:48 +00:00
|
|
|
options,
|
2020-07-21 13:20:51 +00:00
|
|
|
userActions: actions,
|
|
|
|
};
|
|
|
|
|
|
|
|
const result: ApplyUAResult = await new Promise<ApplyUAResult>(
|
|
|
|
(resolve, reject) =>
|
2021-04-26 21:54:09 +00:00
|
|
|
this._sharing.addUserAction({action, docSession, resolve, reject}));
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "_applyUserActions returning %s", shortDesc(result));
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
if (result.isModification) {
|
|
|
|
this._fetchCache.clear(); // This could be more nuanced.
|
2020-10-30 16:53:23 +00:00
|
|
|
this._docManager.markAsChanged(this, 'edit');
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2023-03-20 15:25:09 +00:00
|
|
|
private async _doShutdownImpl(): Promise<void> {
|
|
|
|
const docSession = makeExceptionalDocSession('system');
|
|
|
|
this._log.debug(docSession, "shutdown starting");
|
2023-09-13 05:58:05 +00:00
|
|
|
|
|
|
|
const safeCallAndWait = async (funcDesc: string, func: () => Promise<unknown>) => {
|
|
|
|
try {
|
|
|
|
if (await timeoutReached(Deps.SHUTDOWN_ITEM_TIMEOUT_MS, func())) {
|
|
|
|
this._log.error(docSession, `${funcDesc} timed out`);
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
this._log.error(docSession, `${funcDesc} failed`, err);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-03-20 15:25:09 +00:00
|
|
|
try {
|
|
|
|
this.setMuted();
|
|
|
|
this._inactivityTimer.disable();
|
|
|
|
if (this.docClients.clientCount() > 0) {
|
|
|
|
this._log.warn(docSession, `Doc being closed with ${this.docClients.clientCount()} clients left`);
|
|
|
|
await this.docClients.broadcastDocMessage(null, 'docShutdown', null);
|
|
|
|
this.docClients.interruptAllClients();
|
|
|
|
this.docClients.removeAllClients();
|
|
|
|
}
|
|
|
|
|
|
|
|
this._triggers.shutdown();
|
|
|
|
|
|
|
|
this._redisSubscriber?.quitAsync()
|
|
|
|
.catch(e => this._log.warn(docSession, "Failed to quit redis subscriber", e));
|
|
|
|
|
|
|
|
// Clear the MapWithTTL to remove all timers from the event loop.
|
|
|
|
this._fetchCache.clear();
|
|
|
|
|
2023-09-13 05:58:05 +00:00
|
|
|
await Promise.all(this._intervals.map(interval =>
|
|
|
|
safeCallAndWait("interval.disableAndFinish", () => interval.disableAndFinish())));
|
|
|
|
|
2023-03-20 15:25:09 +00:00
|
|
|
// We'll defer syncing usage until everything is calculated.
|
|
|
|
const usageOptions = {syncUsageToDatabase: false, broadcastUsageToClients: false};
|
|
|
|
|
|
|
|
// This cleanup requires docStorage, which may have failed to start up.
|
|
|
|
// We don't want to log pointless errors in that case.
|
|
|
|
if (this.docStorage.isInitialized()) {
|
|
|
|
// Remove expired attachments, i.e. attachments that were soft deleted a while ago. This
|
|
|
|
// needs to happen periodically, and doing it here means we can guarantee that it happens
|
|
|
|
// even if the doc is only ever opened briefly, without having to slow down startup.
|
2023-09-13 05:58:05 +00:00
|
|
|
await safeCallAndWait("removeUnusedAttachments", () => this.removeUnusedAttachments(true, usageOptions));
|
2023-03-20 15:25:09 +00:00
|
|
|
|
2023-11-13 20:59:23 +00:00
|
|
|
if (this._dataEngine && this._fullyLoaded) {
|
|
|
|
// Note that this must happen before `this._shuttingDown = true` because of this line in Sharing.ts:
|
|
|
|
// if (this._activeDoc.isShuttingDown && isCalculate) {
|
|
|
|
await safeCallAndWait("removeTransformColumns",
|
|
|
|
() => this.applyUserActions(docSession, [["RemoveTransformColumns"]])
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-03-20 15:25:09 +00:00
|
|
|
// Update data size; we'll be syncing both it and attachments size to the database soon.
|
2023-09-13 05:58:05 +00:00
|
|
|
await safeCallAndWait("_updateDataSize", () => this._updateDataSize(usageOptions));
|
2023-03-20 15:25:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
this._syncDocUsageToDatabase(true);
|
2023-04-06 15:10:29 +00:00
|
|
|
this._logDocMetrics(docSession, 'docClose');
|
2023-03-20 15:25:09 +00:00
|
|
|
|
2023-09-13 05:58:05 +00:00
|
|
|
await safeCallAndWait("storageManager.closeDocument",
|
|
|
|
() => this._docManager.storageManager.closeDocument(this.docName));
|
2023-03-20 15:25:09 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
const dataEngine = this._dataEngine ? await this._getEngine() : null;
|
|
|
|
this._shuttingDown = true; // Block creation of engine if not yet in existence.
|
|
|
|
if (dataEngine) {
|
|
|
|
// Give a small grace period for finishing initialization if we are being shut
|
|
|
|
// down while initialization is still in progress, and we don't have an easy
|
|
|
|
// way yet to cancel it cleanly. This is mainly for the benefit of automated
|
|
|
|
// tests.
|
|
|
|
await timeoutReached(3000, this.waitForInitialization());
|
|
|
|
}
|
|
|
|
await Promise.all([
|
|
|
|
this.docStorage.shutdown(),
|
|
|
|
this.docPluginManager?.shutdown(),
|
2023-05-23 19:03:50 +00:00
|
|
|
this._isSnapshot ? undefined : dataEngine?.shutdown(),
|
2023-03-20 15:25:09 +00:00
|
|
|
]);
|
|
|
|
// The this.waitForInitialization promise may not yet have resolved, but
|
|
|
|
// should do so quickly now we've killed everything it depends on.
|
2023-09-13 05:58:05 +00:00
|
|
|
await safeCallAndWait("waitForInitialization", () => this.waitForInitialization());
|
2023-03-20 15:25:09 +00:00
|
|
|
} catch (err) {
|
|
|
|
this._log.error(docSession, "failed to shutdown some resources", err);
|
|
|
|
}
|
2023-09-13 05:58:05 +00:00
|
|
|
// No timeout on this callback: if it hangs, it will make the document unusable.
|
2023-03-20 15:25:09 +00:00
|
|
|
await this._afterShutdownCallback?.();
|
|
|
|
} finally {
|
|
|
|
this._docManager.removeActiveDoc(this);
|
|
|
|
}
|
2023-09-13 05:58:05 +00:00
|
|
|
await safeCallAndWait("_granularAccess.close", () => this._granularAccess.close());
|
2023-03-20 15:25:09 +00:00
|
|
|
this._log.debug(docSession, "shutdown complete");
|
|
|
|
}
|
|
|
|
|
2022-11-15 14:37:48 +00:00
|
|
|
private async _applyUserActionsWithExtendedOptions(docSession: OptDocSession, actions: UserAction[],
|
|
|
|
options?: ApplyUAExtendedOptions): Promise<ApplyUAResult> {
|
|
|
|
assert(Array.isArray(actions), "`actions` parameter should be an array.");
|
|
|
|
// Be careful not to sneak into user action queue before Calculate action, otherwise
|
|
|
|
// there'll be a deadlock.
|
|
|
|
await this.waitForInitialization();
|
|
|
|
|
|
|
|
if (
|
|
|
|
this.dataLimitStatus === "deleteOnly" &&
|
|
|
|
!actions.every(action => [
|
|
|
|
'RemoveTable', 'RemoveColumn', 'RemoveRecord', 'BulkRemoveRecord',
|
|
|
|
'RemoveViewSection', 'RemoveView', 'ApplyUndoActions', 'RespondToRequests',
|
|
|
|
].includes(action[0] as string))
|
|
|
|
) {
|
|
|
|
throw new Error("Document is in delete-only mode");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Granular access control implemented in _applyUserActions.
|
|
|
|
return await this._applyUserActions(docSession, actions, options);
|
|
|
|
}
|
|
|
|
|
2021-10-01 13:45:27 +00:00
|
|
|
/**
|
|
|
|
* Create a new document file without using or initializing the data engine.
|
|
|
|
*/
|
|
|
|
@ActiveDoc.keepDocOpen
|
|
|
|
private async _createDocFile(docSession: OptDocSession, options?: {
|
|
|
|
skipInitialTable?: boolean, // If set, "Table1" will not be added.
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
useExisting?: boolean, // If set, an existing sqlite db is permitted.
|
|
|
|
// Useful for "gristifying" an existing db.
|
2021-10-01 13:45:27 +00:00
|
|
|
}): Promise<void> {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "createDoc");
|
2021-10-01 13:45:27 +00:00
|
|
|
await this._docManager.storageManager.prepareToCreateDoc(this.docName);
|
(core) add a `yarn run cli` tool, and add a `sqlite gristify` option
Summary:
This adds rudimentary support for opening certain SQLite files in Grist.
If you have a file such as `landing.db` in Grist, you can convert it to Grist format by doing (either in monorepo or grist-core):
```
yarn run cli -h
yarn run cli sqlite -h
yarn run cli sqlite gristify landing.db
```
The file is now openable by Grist. To actually do so with the regular Grist server, you'll need to either import it, or convert some doc you don't care about in the `samples/` directory to be a soft link to it (and then force a reload).
This implementation is a rudimentary experiment. Here are some awkwardnesses:
* Only tables that happen to have a column called `id`, and where the column happens to be an integer, can be opened directly with Grist as it is today. That could be generalized, but it looked more than a Gristathon's worth of work, so I instead used SQLite views.
* Grist will handle tables that start with an uncapitalized letter a bit erratically. You can successfully add columns, for example, but removing them will cause sadness - Grist will rename the table in a confused way.
* I didn't attempt to deal with column names with spaces etc (though views could deal with those).
* I haven't tried to do any fancy type mapping.
* Columns with constraints can make adding new rows impossible in Grist, since Grist requires that a row can be added with just a single cell set.
Test Plan: added small test
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3502
2022-07-14 09:32:06 +00:00
|
|
|
await this.docStorage.createFile(options);
|
2021-10-01 13:45:27 +00:00
|
|
|
const sql = options?.skipInitialTable ? GRIST_DOC_SQL : GRIST_DOC_WITH_TABLE1_SQL;
|
|
|
|
await this.docStorage.exec(sql);
|
|
|
|
const timezone = docSession.browserSettings?.timezone ?? DEFAULT_TIMEZONE;
|
|
|
|
const locale = docSession.browserSettings?.locale ?? DEFAULT_LOCALE;
|
2021-11-05 14:36:33 +00:00
|
|
|
const documentSettings: DocumentSettings = { locale };
|
|
|
|
const pythonVersion = process.env.PYTHON_VERSION_ON_CREATION;
|
|
|
|
if (pythonVersion) {
|
|
|
|
if (pythonVersion !== '2' && pythonVersion !== '3') {
|
|
|
|
throw new Error(`PYTHON_VERSION_ON_CREATION must be 2 or 3, not: ${pythonVersion}`);
|
|
|
|
}
|
|
|
|
documentSettings.engine = (pythonVersion === '2') ? 'python2' : 'python3';
|
|
|
|
}
|
2021-10-01 13:45:27 +00:00
|
|
|
await this.docStorage.run('UPDATE _grist_DocInfo SET timezone = ?, documentSettings = ?',
|
2023-05-23 19:17:28 +00:00
|
|
|
timezone, JSON.stringify(documentSettings));
|
2021-10-01 13:45:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private _makeInfo(docSession: OptDocSession, options: ApplyUAOptions = {}) {
|
|
|
|
const client = docSession.client;
|
|
|
|
const user = docSession.mode === 'system' ? 'grist' :
|
|
|
|
(client?.getProfile()?.email || '');
|
|
|
|
return {
|
|
|
|
time: Date.now(),
|
|
|
|
user,
|
|
|
|
inst: this._sharing.instanceId || "unset-inst",
|
|
|
|
desc: options.desc,
|
|
|
|
otherId: options.otherId || 0,
|
|
|
|
linkId: options.linkId || 0,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
/**
|
|
|
|
* Applies all metrics from `usage` to the current document usage state.
|
2022-06-06 16:21:26 +00:00
|
|
|
*
|
|
|
|
* Allows specifying `options` for toggling whether usage is synced to
|
|
|
|
* the home database and/or broadcast to clients.
|
2022-05-16 17:41:12 +00:00
|
|
|
*/
|
2022-06-06 16:21:26 +00:00
|
|
|
private async _updateDocUsage(usage: Partial<DocumentUsage>, options: UpdateUsageOptions = {}) {
|
|
|
|
const {syncUsageToDatabase = true, broadcastUsageToClients = true} = options;
|
|
|
|
const oldStatus = this.dataLimitStatus;
|
2022-05-16 17:41:12 +00:00
|
|
|
this._docUsage = {...(this._docUsage || {}), ...usage};
|
2022-06-06 16:21:26 +00:00
|
|
|
if (syncUsageToDatabase) {
|
|
|
|
/* If status decreased, we'll update usage in the database with minimal delay, so site usage
|
|
|
|
* banners show up-to-date statistics. If status increased or stayed the same, we'll schedule
|
|
|
|
* a delayed update, since it's less critical for banners to update immediately. */
|
|
|
|
const didStatusDecrease = getSeverity(this.dataLimitStatus) < getSeverity(oldStatus);
|
|
|
|
this._syncDocUsageToDatabase(didStatusDecrease);
|
|
|
|
}
|
|
|
|
if (broadcastUsageToClients) {
|
|
|
|
await this._broadcastDocUsageToClients();
|
2022-05-16 17:41:12 +00:00
|
|
|
}
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
private _syncDocUsageToDatabase(minimizeDelay = false) {
|
|
|
|
this._docManager.storageManager.scheduleUsageUpdate(this._docName, this._docUsage, minimizeDelay);
|
2022-03-30 11:45:37 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 16:21:26 +00:00
|
|
|
private async _broadcastDocUsageToClients() {
|
|
|
|
if (this.muted || this.docClients.clientCount() === 0) { return; }
|
|
|
|
|
|
|
|
await this.docClients.broadcastDocMessage(
|
|
|
|
null,
|
|
|
|
'docUsage',
|
|
|
|
{docUsage: this.getDocUsageSummary(), product: this._product},
|
|
|
|
async (session, data) => {
|
|
|
|
return {...data, docUsage: await this.getFilteredDocUsageSummary(session)};
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
private async _updateGracePeriodStart(gracePeriodStart: Date | null) {
|
|
|
|
this._gracePeriodStart = gracePeriodStart;
|
2022-05-16 17:41:12 +00:00
|
|
|
if (!this._isForkOrSnapshot) {
|
|
|
|
await this.getHomeDbManager()?.setDocGracePeriodStart(this.docName, gracePeriodStart);
|
|
|
|
}
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
}
|
|
|
|
|
2022-03-30 11:45:37 +00:00
|
|
|
private async _checkDataLimitRatio() {
|
|
|
|
const exceedingDataLimit = this.dataLimitRatio > 1;
|
|
|
|
if (exceedingDataLimit && !this._gracePeriodStart) {
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
await this._updateGracePeriodStart(new Date());
|
2022-03-30 11:45:37 +00:00
|
|
|
} else if (!exceedingDataLimit && this._gracePeriodStart) {
|
(core) Grace period and delete-only mode when exceeding row limit
Summary:
Builds upon https://phab.getgrist.com/D3328
- Add HomeDB column `Document.gracePeriodStart`
- When the row count moves above the limit, set it to the current date. When it moves below, set it to null.
- Add DataLimitStatus type indicating if the document is approaching the limit, is in a grace period, or is in delete only mode if the grace period started at least 14 days ago. Compute it in ActiveDoc and send it to client when opening.
- Only allow certain user actions when in delete-only mode.
Follow-up tasks related to this diff:
- When DataLimitStatus in the client is non-empty, show a banner to the appropriate users.
- Only send DataLimitStatus to users with the appropriate access. There's no risk landing this now since real users will only see null until free team sites are released.
- Update DataLimitStatus immediately in the client when it changes, e.g. when user actions are applied or the product is changed. Right now it's only sent when the document loads.
- Update row limit, grace period start, and data limit status in ActiveDoc when the product changes, i.e. the user upgrades/downgrades.
- Account for data size when computing data limit status, not just row counts.
See also the tasks mentioned in https://phab.getgrist.com/D3331
Test Plan: Extended FreeTeam nbrowser test, testing the 4 statuses.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D3331
2022-03-24 12:05:51 +00:00
|
|
|
await this._updateGracePeriodStart(null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-30 11:45:37 +00:00
|
|
|
private async _checkDataSizeLimitRatio(docSession: OptDocSession | null) {
|
|
|
|
const start = Date.now();
|
2023-07-20 10:16:58 +00:00
|
|
|
if (!this.docStorage.isInitialized()) {
|
|
|
|
return;
|
|
|
|
}
|
2022-05-16 17:41:12 +00:00
|
|
|
const dataSizeBytes = await this._updateDataSize();
|
2022-03-30 11:45:37 +00:00
|
|
|
const timeToMeasure = Date.now() - start;
|
2022-05-16 17:41:12 +00:00
|
|
|
log.rawInfo('Data size from dbstat...', {
|
|
|
|
...this.getLogMeta(docSession),
|
|
|
|
dataSizeBytes,
|
|
|
|
timeToMeasure,
|
|
|
|
});
|
2022-03-30 11:45:37 +00:00
|
|
|
await this._checkDataLimitRatio();
|
|
|
|
}
|
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
/**
|
2022-06-06 16:21:26 +00:00
|
|
|
* Calculates the total data size in bytes, sets it in _docUsage, and returns it.
|
2022-05-16 17:41:12 +00:00
|
|
|
*
|
2022-06-06 16:21:26 +00:00
|
|
|
* Allows specifying `options` for toggling whether usage is synced to
|
|
|
|
* the home database and/or broadcast to clients.
|
2022-05-16 17:41:12 +00:00
|
|
|
*/
|
2022-06-06 16:21:26 +00:00
|
|
|
private async _updateDataSize(options?: UpdateUsageOptions): Promise<number> {
|
2022-05-16 17:41:12 +00:00
|
|
|
const dataSizeBytes = await this.docStorage.getDataSize();
|
2022-06-06 16:21:26 +00:00
|
|
|
await this._updateDocUsage({dataSizeBytes}, options);
|
2022-05-16 17:41:12 +00:00
|
|
|
return dataSizeBytes;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Prepares a single attachment by adding it DocStorage and returns a UserAction to apply.
|
|
|
|
*/
|
|
|
|
private async _prepAttachment(docSession: OptDocSession, fileData: FileUploadInfo): Promise<UserAction> {
|
|
|
|
// Check that upload size is within the configured limits.
|
|
|
|
const limit = (Number(process.env.GRIST_MAX_UPLOAD_ATTACHMENT_MB) * 1024 * 1024) || Infinity;
|
|
|
|
if (fileData.size > limit) {
|
|
|
|
throw new ApiError(`Attachments must not exceed ${byteString(limit)}`, 413);
|
|
|
|
}
|
|
|
|
|
|
|
|
let dimensions: {width?: number, height?: number} = {};
|
|
|
|
// imageSize returns an object with a width, height and type property if the file is an image.
|
|
|
|
// The width and height properties are integers representing width and height in pixels.
|
|
|
|
try {
|
|
|
|
dimensions = await bluebird.fromCallback((cb: any) => imageSize(fileData.absPath, cb));
|
|
|
|
} catch (err) {
|
|
|
|
// Non-images will fail in some way, and that's OK.
|
|
|
|
dimensions.height = 0;
|
|
|
|
dimensions.width = 0;
|
|
|
|
}
|
|
|
|
const checksum = await checksumFile(fileData.absPath);
|
|
|
|
const fileIdent = checksum + fileData.ext;
|
|
|
|
const ret: boolean = await this.docStorage.findOrAttachFile(fileData.absPath, fileIdent);
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "addAttachment: file %s (image %sx%s) %s", fileIdent,
|
2020-07-21 13:20:51 +00:00
|
|
|
dimensions.width, dimensions.height, ret ? "attached" : "already exists");
|
|
|
|
return ['AddRecord', '_grist_Attachments', null, {
|
|
|
|
fileIdent,
|
|
|
|
fileName: fileData.origName,
|
|
|
|
// We used to set fileType, but it's not easily available for native types. Since it's
|
|
|
|
// also entirely unused, we just skip it until it becomes relevant.
|
|
|
|
fileSize: fileData.size,
|
2023-04-06 15:10:29 +00:00
|
|
|
fileExt: fileData.ext,
|
2020-07-21 13:20:51 +00:00
|
|
|
imageHeight: dimensions.height,
|
|
|
|
imageWidth: dimensions.width,
|
|
|
|
timeUploaded: Date.now()
|
|
|
|
}];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* If the software is newer than the document, migrate the document by fetching all tables, and
|
|
|
|
* giving them to the sandbox so that it can produce migration actions.
|
|
|
|
* TODO: We haven't figured out how to do sharing between different Grist versions that
|
|
|
|
* expect different schema versions. The returned actions at the moment aren't even shared with
|
|
|
|
* collaborators.
|
|
|
|
*/
|
2020-09-02 18:17:17 +00:00
|
|
|
private async _migrate(docSession: OptDocSession): Promise<void> {
|
2020-11-11 21:29:11 +00:00
|
|
|
const tableNames = await this.docStorage.getAllTableNames();
|
|
|
|
|
|
|
|
// Fetch only metadata tables first, and try to migrate with only those.
|
|
|
|
const tableData: {[key: string]: Buffer|null} = {};
|
|
|
|
for (const tableName of tableNames) {
|
|
|
|
if (tableName.startsWith('_grist_')) {
|
|
|
|
tableData[tableName] = await this.docStorage.fetchTable(tableName);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let docActions: DocAction[];
|
|
|
|
try {
|
|
|
|
// The last argument tells create_migrations() that only metadata is included.
|
2020-12-07 21:15:58 +00:00
|
|
|
docActions = await this._rawPyCall('create_migrations', tableData, true);
|
2020-11-11 21:29:11 +00:00
|
|
|
} catch (e) {
|
|
|
|
if (!/need all tables/.test(e.message)) {
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
// If the migration failed because it needs all tables (i.e. involves changes to data), then
|
|
|
|
// fetch them all. TODO: This is used for some older migrations, and is relied on by tests.
|
|
|
|
// If a new migration needs this flag, more work is needed. The current approach creates
|
|
|
|
// more memory pressure than usual since full data is present in memory at once both in node
|
|
|
|
// and in Python; and it doesn't skip onDemand tables. This is liable to cause crashes.
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.warn(docSession, "_migrate: retrying with all tables");
|
2020-11-11 21:29:11 +00:00
|
|
|
for (const tableName of tableNames) {
|
|
|
|
if (!tableData[tableName] && !tableName.startsWith('_gristsys_')) {
|
|
|
|
tableData[tableName] = await this.docStorage.fetchTable(tableName);
|
|
|
|
}
|
|
|
|
}
|
2020-12-07 21:15:58 +00:00
|
|
|
docActions = await this._rawPyCall('create_migrations', tableData);
|
2020-11-11 21:29:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const processedTables = Object.keys(tableData);
|
|
|
|
const numSchema = countIf(processedTables, t => t.startsWith("_grist_"));
|
|
|
|
const numUser = countIf(processedTables, t => !t.startsWith("_grist_"));
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "_migrate: applying %d migration actions (processed %s schema, %s user tables)",
|
2020-11-11 21:29:11 +00:00
|
|
|
docActions.length, numSchema, numUser);
|
|
|
|
|
2021-10-25 13:29:06 +00:00
|
|
|
docActions.forEach((action, i) => this._log.info(docSession, "_migrate: docAction %s: %s", i, shortDesc(action)));
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.docStorage.execTransaction(() => this.docStorage.applyStoredActions(docActions));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Load the specified tables into the data engine.
|
|
|
|
*/
|
|
|
|
private async _loadTables(docSession: OptDocSession, tableNames: string[]) {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "loading %s tables: %s", tableNames.length,
|
2020-07-21 13:20:51 +00:00
|
|
|
tableNames.join(", "));
|
|
|
|
// Pass the resulting array to `map`, which allows parallel processing of the tables. Database
|
|
|
|
// and DataEngine may still do things serially, but it allows them to be busy simultaneously.
|
|
|
|
await bluebird.map(tableNames, async (tableName: string) =>
|
2020-12-07 21:15:58 +00:00
|
|
|
this._pyCall('load_table', tableName, await this._fetchTableIfPresent(tableName)),
|
2020-07-21 13:20:51 +00:00
|
|
|
// How many tables to query for and push to the data engine in parallel.
|
|
|
|
{ concurrency: 3 });
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2021-10-01 13:45:27 +00:00
|
|
|
/**
|
|
|
|
* Start loading the specified tables from the db, without waiting for completion.
|
|
|
|
* The loader can be directed to stream the tables on to the engine.
|
|
|
|
*/
|
|
|
|
private _startLoadingTables(docSession: OptDocSession, tableNames: string[]) {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.debug(docSession, "starting to load %s tables: %s", tableNames.length,
|
2021-10-01 13:45:27 +00:00
|
|
|
tableNames.join(", "));
|
|
|
|
for (const tableId of tableNames) {
|
|
|
|
this._tableMetadataLoader.startFetchingTable(tableId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Fetches and returns the requested table, or null if it's missing. This allows documents to
|
|
|
|
// load with missing metadata tables (should only matter if migrations are also broken).
|
|
|
|
private async _fetchTableIfPresent(tableName: string): Promise<Buffer|null> {
|
|
|
|
try {
|
|
|
|
return await this.docStorage.fetchTable(tableName);
|
|
|
|
} catch (err) {
|
|
|
|
if (/no such table/.test(err.message)) { return null; }
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// It's a bit risky letting "Calculate" (and other formula-dependent calls) to disable
|
|
|
|
// inactivityTimer, since a user formulas with an infinite loop can disable it forever.
|
|
|
|
// TODO find a solution to this issue.
|
|
|
|
@ActiveDoc.keepDocOpen
|
(core) Log statistics about table sizes
Summary:
Record numbers of rows, columns, cells, and bytes of marshalled data for most calls to table_data_from_db
Export new function get_table_stats in the sandbox, which gives the raw numbers and totals.
Get and log these stats in ActiveDoc right after loading tables, before Calculate, so they are logged even in case of errors.
Tweak logging about number of tables, especially number of on-demand tables, to not only show in debug logging.
Test Plan: Updated doc regression tests, that shows what the data looks like nicely.
Reviewers: dsagal, paulfitz
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D3081
2021-10-21 13:03:37 +00:00
|
|
|
private async _finishInitialization(
|
|
|
|
docSession: OptDocSession, pendingTableNames: string[], onDemandNames: string[], startTime: number
|
2022-03-24 20:27:34 +00:00
|
|
|
): Promise<void> {
|
2020-07-21 13:20:51 +00:00
|
|
|
try {
|
2021-10-01 13:45:27 +00:00
|
|
|
await this._tableMetadataLoader.wait();
|
|
|
|
await this._tableMetadataLoader.clean();
|
(core) Log statistics about table sizes
Summary:
Record numbers of rows, columns, cells, and bytes of marshalled data for most calls to table_data_from_db
Export new function get_table_stats in the sandbox, which gives the raw numbers and totals.
Get and log these stats in ActiveDoc right after loading tables, before Calculate, so they are logged even in case of errors.
Tweak logging about number of tables, especially number of on-demand tables, to not only show in debug logging.
Test Plan: Updated doc regression tests, that shows what the data looks like nicely.
Reviewers: dsagal, paulfitz
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D3081
2021-10-21 13:03:37 +00:00
|
|
|
|
2023-05-23 19:03:50 +00:00
|
|
|
if (this._isSnapshot) {
|
|
|
|
log.rawInfo("Loading complete", {
|
|
|
|
...this.getLogMeta(docSession),
|
|
|
|
num_on_demand_tables: onDemandNames.length,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
await this._loadTables(docSession, pendingTableNames);
|
|
|
|
const tableStats = await this._pyCall('get_table_stats');
|
|
|
|
log.rawInfo("Loading complete, table statistics retrieved...", {
|
|
|
|
...this.getLogMeta(docSession),
|
|
|
|
...tableStats,
|
|
|
|
num_on_demand_tables: onDemandNames.length,
|
|
|
|
});
|
|
|
|
await this._pyCall('initialize', this._options?.docUrl);
|
(core) Log statistics about table sizes
Summary:
Record numbers of rows, columns, cells, and bytes of marshalled data for most calls to table_data_from_db
Export new function get_table_stats in the sandbox, which gives the raw numbers and totals.
Get and log these stats in ActiveDoc right after loading tables, before Calculate, so they are logged even in case of errors.
Tweak logging about number of tables, especially number of on-demand tables, to not only show in debug logging.
Test Plan: Updated doc regression tests, that shows what the data looks like nicely.
Reviewers: dsagal, paulfitz
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D3081
2021-10-21 13:03:37 +00:00
|
|
|
|
2023-05-23 19:03:50 +00:00
|
|
|
// Calculations are not associated specifically with the user opening the document.
|
|
|
|
// TODO: be careful with which users can create formulas.
|
|
|
|
await this._applyUserActions(makeExceptionalDocSession('system'), [['Calculate']]);
|
|
|
|
await this._reportDataEngineMemory();
|
|
|
|
}
|
(core) get all tests working under python3/gvisor
Summary:
This verifies that all existing tests are capable of running under python3/gvisor, and fixes the small issues that came up. It does not yet activate python3 tests on all diffs, only diffs that specifically request them.
* Adds a suffix in test names and output directories for tests run with PYTHON_VERSION=3, so that results of the same test run with and without the flag can be aggregated cleanly.
* Adds support for checkpointing to the gvisor sandbox adapter.
* Prepares a checkpoint made after grist python code has loaded in the gvisor sandbox.
* Changes how `DOC_URL` is passed to the sandbox, since it can no longer be passed in as an environment variable when using checkpoints.
* Uses the checkpoint to speed up tests using the gvisor sandbox, otherwise a lot of tests need more time (especially on mac under docker).
* Directs jenkins to run all tests with python2 and python3 when a new file `buildtools/changelogs/python.txt` is touched (this diff counts as touching that file).
* Tweaks miscellaneous tests
- some needed fixes exposed by slightly different timing
- a small number actually give different results in py3 (removal of `u` prefixes).
- some needed a little more time
The DOC_URL change is not the ultimate solution we want for DOC_URL. Eventually it should be a variable that gets updated, like the date perhaps. This is just a small pragmatic change to preserve existing behavior.
Tests are run mindlessly as py3, and for some tests it won't change anything (e.g. if they do not use NSandbox). Tests are not run in parallel, doubling overall test time.
Checkpoints could be useful in deployment, though this diff doesn't use them there.
The application of checkpoints doesn't check for other configuration like 3-versus-5-pipe that we don't actually use.
Python2 tests run using pynbox as always for now.
The diff got sufficiently bulky that I didn't tackle running py3 on "regular" diffs in it. My preference, given that most tests don't appear to stress the python side of things, would be to make a selection of the tests that do and a few wild cards, and run those tests on both pythons rather then all of them. For diffs making a significant python change, I'd propose touching buildtools/changelogs/python.txt for full tests. But this is a conversation in progress.
A total of 6886 tests ran on this diff.
Test Plan: this is a step in preparing tests for py3 transition
Reviewers: dsagal
Reviewed By: dsagal
Subscribers: dsagal
Differential Revision: https://phab.getgrist.com/D3066
2021-10-18 17:37:51 +00:00
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
this._fullyLoaded = true;
|
|
|
|
const endTime = Date.now();
|
|
|
|
const loadMs = endTime - startTime;
|
|
|
|
// Adjust the inactivity timer: if the load took under 1 sec, use the regular timeout; if it
|
|
|
|
// took longer, scale it up proportionately.
|
|
|
|
const closeTimeout = Math.max(loadMs, 1000) * Deps.ACTIVEDOC_TIMEOUT;
|
|
|
|
this._inactivityTimer.setDelay(closeTimeout);
|
2024-01-24 17:20:47 +00:00
|
|
|
log.rawDebug('ActiveDoc load timing', {
|
|
|
|
...this.getLogMeta(docSession),
|
|
|
|
loadMs,
|
|
|
|
closeTimeout,
|
|
|
|
});
|
(core) notify home db of shares when copying/forking/uploading docs
Summary:
The first time a worker opens a document, it will now check if it has any shares the home db needs to be aware of. If so, they will be added. This is important for documents uploaded/copied/forked/replaced, so that their shares work out of the box.
In future, may want some UI to give user control of whether shares are activated after upload/copy/fork/replace.
It seems tricky currently to know if a document is being opened for the first time. As a proxy, I check whether usage information has been calculated and saved to the db, since I can determine that without adding another db query. It is safe to synchronize shares more than necessary.
This leaves two gaps:
* If a document is created/uploaded/copied/forked/replaced and no attempt is made to access it prior to using a share, then that share won't actually be available. Not a problem currently I think, since how would a user have determined the share key. But in future it would be good to also do a sync after creation/upload/copy/fork/replacement/...
* On document replacement, usage info is reset but not absolutely immediately. So in principle shares could fail to be created on first load of the replacement. Usage info reset could be tweaked to give a guarantee here, but also fixing the first point would resolve this second point too.
Test Plan: copy test added
Reviewers: georgegevoian
Reviewed By: georgegevoian
Differential Revision: https://phab.getgrist.com/D4165
2024-01-12 22:05:13 +00:00
|
|
|
const docUsage = getDocSessionUsage(docSession);
|
|
|
|
if (!docUsage) {
|
|
|
|
// This looks be the first time this installation of Grist is touching
|
|
|
|
// the document. If it has any shares, the home db needs to know.
|
|
|
|
// TODO: could offer a UI to control whether shares are activated.
|
|
|
|
await this.syncShares(docSession, { skipIfNoShares: true });
|
|
|
|
}
|
2022-06-06 16:21:26 +00:00
|
|
|
void this._initializeDocUsage(docSession);
|
2023-09-13 05:58:05 +00:00
|
|
|
|
|
|
|
// Start the periodic work, unless this doc has already started shutting down.
|
|
|
|
if (!this.muted) {
|
|
|
|
for (const interval of this._intervals) {
|
|
|
|
interval.enable();
|
|
|
|
}
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
} catch (err) {
|
2022-03-24 20:27:34 +00:00
|
|
|
this._fullyLoaded = true;
|
2021-09-15 23:35:21 +00:00
|
|
|
if (!this._shuttingDown) {
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.warn(docSession, "_finishInitialization stopped with %s", err);
|
2022-03-24 20:27:34 +00:00
|
|
|
throw new Error('ActiveDoc initialization failed: ' + String(err));
|
2021-09-15 23:35:21 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-06 15:10:29 +00:00
|
|
|
private _logDocMetrics(docSession: OptDocSession, triggeredBy: 'docOpen' | 'interval'| 'docClose') {
|
|
|
|
this.logTelemetryEvent(docSession, 'documentUsage', {
|
2023-06-06 17:08:50 +00:00
|
|
|
limited: {
|
|
|
|
triggeredBy,
|
|
|
|
isPublic: ((this._doc as unknown) as APIDocument)?.public ?? false,
|
|
|
|
rowCount: this._docUsage?.rowCount?.total,
|
|
|
|
dataSizeBytes: this._docUsage?.dataSizeBytes,
|
|
|
|
attachmentsSize: this._docUsage?.attachmentsSizeBytes,
|
|
|
|
...this._getAccessRuleMetrics(),
|
|
|
|
...this._getAttachmentMetrics(),
|
|
|
|
...this._getChartMetrics(),
|
|
|
|
...this._getWidgetMetrics(),
|
|
|
|
...this._getColumnMetrics(),
|
|
|
|
...this._getTableMetrics(),
|
|
|
|
...this._getCustomWidgetMetrics(),
|
|
|
|
},
|
2023-04-06 15:10:29 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getAccessRuleMetrics() {
|
|
|
|
const accessRules = this.docData?.getMetaTable('_grist_ACLRules');
|
|
|
|
const numAccessRules = accessRules?.numRecords() ?? 0;
|
|
|
|
const numUserAttributes = accessRules?.getRecords().filter(r => r.userAttributes).length ?? 0;
|
|
|
|
|
|
|
|
return {
|
|
|
|
numAccessRules,
|
|
|
|
numUserAttributes,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getAttachmentMetrics() {
|
|
|
|
const attachments = this.docData?.getMetaTable('_grist_Attachments');
|
|
|
|
const numAttachments = attachments?.numRecords() ?? 0;
|
|
|
|
const attachmentTypes = attachments?.getRecords()
|
2023-04-19 04:27:18 +00:00
|
|
|
// Exclude the leading ".", if any.
|
|
|
|
.map(r => r.fileExt?.trim()?.slice(1))
|
|
|
|
.filter(ext => Boolean(ext));
|
2023-06-06 17:08:50 +00:00
|
|
|
const uniqueAttachmentTypes = [...new Set(attachmentTypes ?? [])];
|
2023-04-06 15:10:29 +00:00
|
|
|
return {
|
|
|
|
numAttachments,
|
2023-06-06 17:08:50 +00:00
|
|
|
attachmentTypes: uniqueAttachmentTypes,
|
2023-04-06 15:10:29 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getChartMetrics() {
|
|
|
|
const viewSections = this.docData?.getMetaTable('_grist_Views_section');
|
|
|
|
const viewSectionRecords = viewSections?.getRecords() ?? [];
|
|
|
|
const chartRecords = viewSectionRecords?.filter(r => r.parentKey === 'chart') ?? [];
|
|
|
|
const chartTypes = chartRecords.map(r => r.chartType || 'bar');
|
|
|
|
const numCharts = chartRecords.length;
|
|
|
|
const numLinkedCharts = chartRecords.filter(r => r.linkSrcSectionRef).length;
|
|
|
|
|
|
|
|
return {
|
|
|
|
numCharts,
|
|
|
|
chartTypes,
|
|
|
|
numLinkedCharts,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getWidgetMetrics() {
|
|
|
|
const viewSections = this.docData?.getMetaTable('_grist_Views_section');
|
|
|
|
const viewSectionRecords = viewSections?.getRecords() ?? [];
|
|
|
|
const numLinkedWidgets = viewSectionRecords.filter(r => r.linkSrcSectionRef).length;
|
|
|
|
|
|
|
|
return {
|
|
|
|
numLinkedWidgets,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getColumnMetrics() {
|
|
|
|
const columns = this.docData?.getMetaTable('_grist_Tables_column');
|
|
|
|
const columnRecords = columns?.getRecords().filter(r => !isHiddenCol(r.colId)) ?? [];
|
|
|
|
const numColumns = columnRecords.length;
|
|
|
|
const numColumnsWithConditionalFormatting = columnRecords.filter(r => r.rules).length;
|
|
|
|
const numFormulaColumns = columnRecords.filter(r => r.isFormula && r.formula).length;
|
|
|
|
const numTriggerFormulaColumns = columnRecords.filter(r => !r.isFormula && r.formula).length;
|
|
|
|
|
|
|
|
const tables = this.docData?.getMetaTable('_grist_Tables');
|
|
|
|
const tableRecords = tables?.getRecords().filter(r =>
|
|
|
|
r.tableId && !r.tableId.startsWith('GristHidden_')) ?? [];
|
|
|
|
const summaryTables = tableRecords.filter(r => r.summarySourceTable);
|
|
|
|
const summaryTableIds = new Set([...summaryTables.map(t => t.id)]);
|
|
|
|
const numSummaryFormulaColumns = columnRecords.filter(r =>
|
|
|
|
r.isFormula && summaryTableIds.has(r.parentId)).length;
|
|
|
|
|
|
|
|
const viewSectionFields = this.docData?.getMetaTable('_grist_Views_section_field');
|
|
|
|
const viewSectionFieldRecords = viewSectionFields?.getRecords() ?? [];
|
|
|
|
const numFieldsWithConditionalFormatting = viewSectionFieldRecords.filter(r => r.rules).length;
|
|
|
|
|
|
|
|
return {
|
|
|
|
numColumns,
|
|
|
|
numColumnsWithConditionalFormatting,
|
|
|
|
numFormulaColumns,
|
|
|
|
numTriggerFormulaColumns,
|
|
|
|
numSummaryFormulaColumns,
|
|
|
|
numFieldsWithConditionalFormatting,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getTableMetrics() {
|
|
|
|
const tables = this.docData?.getMetaTable('_grist_Tables');
|
|
|
|
const tableRecords = tables?.getRecords().filter(r =>
|
|
|
|
r.tableId && !r.tableId.startsWith('GristHidden_')) ?? [];
|
|
|
|
const numTables = tableRecords.length;
|
|
|
|
const numOnDemandTables = tableRecords.filter(r => r.onDemand).length;
|
|
|
|
|
|
|
|
const viewSections = this.docData?.getMetaTable('_grist_Views_section');
|
|
|
|
const viewSectionRecords = viewSections?.getRecords() ?? [];
|
|
|
|
const numTablesWithConditionalFormatting = viewSectionRecords.filter(r => r.rules).length;
|
|
|
|
|
|
|
|
const summaryTables = tableRecords.filter(r => r.summarySourceTable);
|
|
|
|
const numSummaryTables = summaryTables.length;
|
|
|
|
|
|
|
|
return {
|
|
|
|
numTables,
|
|
|
|
numOnDemandTables,
|
|
|
|
numTablesWithConditionalFormatting,
|
|
|
|
numSummaryTables,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getCustomWidgetMetrics() {
|
|
|
|
const viewSections = this.docData?.getMetaTable('_grist_Views_section');
|
|
|
|
const viewSectionRecords = viewSections?.getRecords() ?? [];
|
2023-05-18 22:35:39 +00:00
|
|
|
const customWidgetIds: string[] = [];
|
2023-04-06 15:10:29 +00:00
|
|
|
for (const r of viewSectionRecords) {
|
|
|
|
const {customView} = safeJsonParse(r.options, {});
|
|
|
|
if (!customView) { continue; }
|
|
|
|
|
2023-05-18 22:35:39 +00:00
|
|
|
const {pluginId, url} = safeJsonParse(customView, {});
|
2023-04-06 15:10:29 +00:00
|
|
|
if (!url) { continue; }
|
|
|
|
|
2023-05-18 22:35:39 +00:00
|
|
|
const isGristLabsWidget = url.startsWith(commonUrls.gristLabsCustomWidgets);
|
|
|
|
customWidgetIds.push(isGristLabsWidget ? pluginId : 'externalId');
|
2023-04-06 15:10:29 +00:00
|
|
|
}
|
2023-05-18 22:35:39 +00:00
|
|
|
const numCustomWidgets = customWidgetIds.length;
|
2023-04-06 15:10:29 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
numCustomWidgets,
|
2023-05-18 22:35:39 +00:00
|
|
|
customWidgetIds,
|
2023-04-06 15:10:29 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-08-10 18:21:03 +00:00
|
|
|
private async _fetchQueryFromDB(query: ServerQuery, onDemand: boolean): Promise<TableDataAction> {
|
2020-07-21 13:20:51 +00:00
|
|
|
// Expand query to compute formulas (or include placeholders for them).
|
|
|
|
const expandedQuery = expandQuery(query, this.docData!, onDemand);
|
|
|
|
const marshalled = await this.docStorage.fetchQuery(expandedQuery);
|
|
|
|
const table = this.docStorage.decodeMarshalledData(marshalled, query.tableId);
|
|
|
|
|
|
|
|
// Substitute in constant values for errors / placeholders.
|
|
|
|
if (expandedQuery.constants) {
|
|
|
|
for (const colId of Object.keys(expandedQuery.constants)) {
|
|
|
|
const constant = expandedQuery.constants[colId];
|
|
|
|
table[colId] = table[colId].map(() => constant);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return toTableDataAction(query.tableId, table);
|
|
|
|
}
|
|
|
|
|
2021-08-10 18:21:03 +00:00
|
|
|
private async _fetchQueryFromDataEngine(query: ServerQuery): Promise<TableDataAction> {
|
2020-12-07 21:15:58 +00:00
|
|
|
return this._pyCall('fetch_table', query.tableId, true, query.filters);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private async _reportDataEngineMemory() {
|
|
|
|
const now = Date.now();
|
|
|
|
if (now >= this._lastMemoryMeasurement + MEMORY_MEASUREMENT_INTERVAL_MS) {
|
|
|
|
this._lastMemoryMeasurement = now;
|
2021-09-15 23:35:21 +00:00
|
|
|
if (this._dataEngine && !this._shuttingDown) {
|
|
|
|
const dataEngine = await this._getEngine();
|
|
|
|
await dataEngine.reportMemoryUsage();
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-06 16:21:26 +00:00
|
|
|
private async _initializeDocUsage(docSession: OptDocSession) {
|
|
|
|
const promises: Promise<unknown>[] = [];
|
|
|
|
// We'll defer syncing/broadcasting usage until everything is calculated.
|
|
|
|
const options = {syncUsageToDatabase: false, broadcastUsageToClients: false};
|
2022-05-16 17:41:12 +00:00
|
|
|
if (this._docUsage?.dataSizeBytes === undefined) {
|
2022-06-06 16:21:26 +00:00
|
|
|
promises.push(this._updateDataSize(options));
|
2022-05-16 17:41:12 +00:00
|
|
|
}
|
|
|
|
if (this._docUsage?.attachmentsSizeBytes === undefined) {
|
2022-06-06 16:21:26 +00:00
|
|
|
promises.push(this._updateAttachmentsSize(options));
|
|
|
|
}
|
2023-04-06 15:10:29 +00:00
|
|
|
if (promises.length === 0) {
|
|
|
|
this._logDocMetrics(docSession, 'docOpen');
|
|
|
|
return;
|
|
|
|
}
|
2022-06-06 16:21:26 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
await Promise.all(promises);
|
|
|
|
this._syncDocUsageToDatabase();
|
|
|
|
await this._broadcastDocUsageToClients();
|
|
|
|
} catch (e) {
|
|
|
|
this._log.warn(docSession, 'failed to initialize doc usage', e);
|
2022-05-16 17:41:12 +00:00
|
|
|
}
|
2023-04-06 15:10:29 +00:00
|
|
|
|
|
|
|
this._logDocMetrics(docSession, 'docOpen');
|
|
|
|
}
|
|
|
|
|
2023-06-06 17:08:50 +00:00
|
|
|
private _getTelemetryMeta(docSession: OptDocSession|null): TelemetryMetadataByLevel {
|
2023-05-18 22:35:39 +00:00
|
|
|
const altSessionId = docSession ? getDocSessionAltSessionId(docSession) : undefined;
|
|
|
|
return merge(
|
|
|
|
docSession ? getTelemetryMetaFromDocSession(docSession) : {},
|
2023-06-06 17:08:50 +00:00
|
|
|
altSessionId ? {altSessionId} : {},
|
2023-05-18 22:35:39 +00:00
|
|
|
{
|
2023-06-06 17:08:50 +00:00
|
|
|
limited: {
|
2023-07-04 21:21:34 +00:00
|
|
|
docIdDigest: this._docName,
|
2023-06-06 17:08:50 +00:00
|
|
|
},
|
|
|
|
full: {
|
|
|
|
siteId: this._doc?.workspace.org.id,
|
|
|
|
siteType: this._product?.name,
|
|
|
|
},
|
2023-05-18 22:35:39 +00:00
|
|
|
},
|
|
|
|
);
|
2022-05-16 17:41:12 +00:00
|
|
|
}
|
|
|
|
|
2020-10-30 16:53:23 +00:00
|
|
|
/**
|
|
|
|
* Called before a migration. Makes sure a back-up is made.
|
|
|
|
*/
|
|
|
|
private async _beforeMigration(docSession: OptDocSession, versionType: 'storage' | 'schema',
|
|
|
|
currentVersion: number, newVersion: number) {
|
|
|
|
this._migrating++;
|
|
|
|
const label = `migrate-${versionType}-last-v${currentVersion}-before-v${newVersion}`;
|
|
|
|
this._docManager.markAsChanged(this); // Give backup current time.
|
|
|
|
const location = await this._docManager.makeBackup(this, label);
|
2021-10-25 13:29:06 +00:00
|
|
|
this._log.info(docSession, "_beforeMigration: backup made with label %s at %s", label, location);
|
2020-10-30 16:53:23 +00:00
|
|
|
this.emit("backupMade", location);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Called after a migration.
|
|
|
|
*/
|
|
|
|
private async _afterMigration(docSession: OptDocSession, versionType: 'storage' | 'schema',
|
|
|
|
newVersion: number, success: boolean) {
|
|
|
|
this._migrating--;
|
|
|
|
// Mark as changed even if migration is not successful, out of caution.
|
|
|
|
if (!this._migrating) { this._docManager.markAsChanged(this); }
|
|
|
|
}
|
2020-12-07 21:15:58 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Call a method in the sandbox, without checking the _modificationLock. Calls to
|
|
|
|
* the sandbox are naturally serialized.
|
|
|
|
*/
|
2021-09-15 23:35:21 +00:00
|
|
|
private async _rawPyCall(funcName: string, ...varArgs: unknown[]): Promise<any> {
|
|
|
|
const dataEngine = await this._getEngine();
|
2023-05-23 19:03:50 +00:00
|
|
|
try {
|
|
|
|
return await dataEngine.pyCall(funcName, ...varArgs);
|
|
|
|
} catch (e) {
|
|
|
|
if (e instanceof UnavailableSandboxMethodError && this._isSnapshot) {
|
|
|
|
throw new UnavailableSandboxMethodError('pyCall is not available in snapshots');
|
|
|
|
}
|
|
|
|
|
|
|
|
throw e;
|
|
|
|
}
|
2020-12-07 21:15:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Call a method in the sandbox, while checking on the _modificationLock. If the
|
|
|
|
* lock is held, the call will wait until the lock is released, and then hold
|
|
|
|
* the lock itself while operating.
|
|
|
|
*/
|
|
|
|
private _pyCall(funcName: string, ...varArgs: unknown[]): Promise<any> {
|
|
|
|
return this._modificationLock.runExclusive(() => this._rawPyCall(funcName, ...varArgs));
|
|
|
|
}
|
2021-09-15 23:35:21 +00:00
|
|
|
|
|
|
|
private async _getEngine(): Promise<ISandbox> {
|
|
|
|
if (this._shuttingDown) { throw new Error('shutting down, data engine unavailable'); }
|
2023-05-23 19:03:50 +00:00
|
|
|
if (this._dataEngine) { return this._dataEngine; }
|
|
|
|
|
|
|
|
this._dataEngine = this._isSnapshot ? this._makeNullEngine() : this._makeEngine();
|
2021-10-01 13:45:27 +00:00
|
|
|
return this._dataEngine;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _makeEngine(): Promise<ISandbox> {
|
|
|
|
// Figure out what kind of engine we need for this document.
|
2021-10-07 17:49:23 +00:00
|
|
|
let preferredPythonVersion: '2' | '3' = process.env.PYTHON_VERSION === '3' ? '3' : '2';
|
2021-10-01 13:45:27 +00:00
|
|
|
|
2021-11-05 14:36:33 +00:00
|
|
|
// Careful, migrations may not have run on this document and it may not have a
|
|
|
|
// documentSettings column. Failures are treated as lack of an engine preference.
|
|
|
|
const docInfo = await this.docStorage.get('SELECT documentSettings FROM _grist_DocInfo').catch(e => undefined);
|
|
|
|
const docSettingsString = docInfo?.documentSettings;
|
|
|
|
if (docSettingsString) {
|
|
|
|
const docSettings: DocumentSettings|undefined = safeJsonParse(docSettingsString, undefined);
|
|
|
|
const engine = docSettings?.engine;
|
|
|
|
if (engine) {
|
|
|
|
if (engine === 'python2') {
|
|
|
|
preferredPythonVersion = '2';
|
|
|
|
} else if (engine === 'python3') {
|
|
|
|
preferredPythonVersion = '3';
|
|
|
|
} else {
|
|
|
|
throw new Error(`engine type not recognized: ${engine}`);
|
2021-09-15 23:35:21 +00:00
|
|
|
}
|
|
|
|
}
|
2021-10-01 13:45:27 +00:00
|
|
|
}
|
|
|
|
return this._docManager.gristServer.create.NSandbox({
|
|
|
|
comment: this._docName,
|
|
|
|
logCalls: false,
|
|
|
|
logTimes: true,
|
|
|
|
logMeta: {docId: this._docName},
|
|
|
|
preferredPythonVersion,
|
2022-02-04 11:13:03 +00:00
|
|
|
sandboxOptions: {
|
|
|
|
exports: {
|
2022-06-17 18:49:18 +00:00
|
|
|
request: (key: string, args: SandboxRequest) => this._requests.handleSingleRequestWithCache(key, args),
|
2023-06-07 18:19:10 +00:00
|
|
|
guessColInfo,
|
|
|
|
convertFromColumn,
|
2022-02-04 11:13:03 +00:00
|
|
|
}
|
|
|
|
},
|
2021-09-15 23:35:21 +00:00
|
|
|
});
|
|
|
|
}
|
2022-04-14 12:19:36 +00:00
|
|
|
|
2023-05-23 19:03:50 +00:00
|
|
|
private async _makeNullEngine(): Promise<ISandbox> {
|
|
|
|
return new NullSandbox();
|
|
|
|
}
|
|
|
|
|
2022-04-14 12:19:36 +00:00
|
|
|
/**
|
|
|
|
* Throw an error if the provided upload would exceed the total attachment filesize limit for this document.
|
|
|
|
*/
|
2022-05-03 05:20:31 +00:00
|
|
|
private async _assertUploadSizeBelowLimit(upload: UploadInfo) {
|
2022-04-14 12:19:36 +00:00
|
|
|
// Minor flaw: while we don't double-count existing duplicate files in the total size,
|
|
|
|
// we don't check here if any of the uploaded files already exist and could be left out of the calculation.
|
2022-05-03 05:20:31 +00:00
|
|
|
const uploadSizeBytes = sum(upload.files.map(f => f.size));
|
|
|
|
if (await this._isUploadSizeBelowLimit(uploadSizeBytes)) { return; }
|
2022-04-14 12:19:36 +00:00
|
|
|
|
2022-05-03 05:20:31 +00:00
|
|
|
// TODO probably want a nicer error message here.
|
|
|
|
throw new LimitExceededError("Exceeded attachments limit for document");
|
|
|
|
}
|
2022-04-14 12:19:36 +00:00
|
|
|
|
2022-05-03 05:20:31 +00:00
|
|
|
/**
|
|
|
|
* Returns true if an upload with size `uploadSizeBytes` won't cause attachment size
|
|
|
|
* limits to be exceeded.
|
|
|
|
*/
|
|
|
|
private async _isUploadSizeBelowLimit(uploadSizeBytes: number): Promise<boolean> {
|
2022-06-06 16:21:26 +00:00
|
|
|
const maxSize = this._product?.features.baseMaxAttachmentsBytesPerDocument;
|
2022-05-03 05:20:31 +00:00
|
|
|
if (!maxSize) { return true; }
|
2022-04-14 12:19:36 +00:00
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
let currentSize = this._docUsage?.attachmentsSizeBytes;
|
|
|
|
currentSize = currentSize ?? await this._updateAttachmentsSize({syncUsageToDatabase: false});
|
2022-05-03 05:20:31 +00:00
|
|
|
return currentSize + uploadSizeBytes <= maxSize;
|
|
|
|
}
|
2022-04-14 12:19:36 +00:00
|
|
|
|
2022-05-16 17:41:12 +00:00
|
|
|
/**
|
2022-06-06 16:21:26 +00:00
|
|
|
* Calculates the total attachments size in bytes, sets it in _docUsage, and returns it.
|
2022-05-16 17:41:12 +00:00
|
|
|
*
|
2022-06-06 16:21:26 +00:00
|
|
|
* Allows specifying `options` for toggling whether usage is synced to
|
|
|
|
* the home database and/or broadcast to clients.
|
2022-05-16 17:41:12 +00:00
|
|
|
*/
|
2022-06-06 16:21:26 +00:00
|
|
|
private async _updateAttachmentsSize(options?: UpdateUsageOptions): Promise<number> {
|
2022-05-16 17:41:12 +00:00
|
|
|
const attachmentsSizeBytes = await this.docStorage.getTotalAttachmentFileSizes();
|
2022-06-06 16:21:26 +00:00
|
|
|
await this._updateDocUsage({attachmentsSizeBytes}, options);
|
2022-05-16 17:41:12 +00:00
|
|
|
return attachmentsSizeBytes;
|
2022-04-14 12:19:36 +00:00
|
|
|
}
|
2022-12-21 16:40:00 +00:00
|
|
|
|
|
|
|
private _getCachedAttachmentColumns(): AttachmentColumns {
|
|
|
|
if (!this.docData) { return new Map(); }
|
|
|
|
if (!this._attachmentColumns) {
|
|
|
|
this._attachmentColumns = getAttachmentColumns(this.docData);
|
|
|
|
}
|
|
|
|
return this._attachmentColumns;
|
|
|
|
}
|
2023-05-23 19:03:50 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Waits for the data engine to be ready before calling `cb`, creating the
|
|
|
|
* engine if needed.
|
|
|
|
*
|
|
|
|
* Optionally shuts down and removes the engine after.
|
|
|
|
*
|
|
|
|
* NOTE: This method should be used with care, particularly when `shutdownAfter`
|
|
|
|
* is set. Currently, it's only used to run migrations on snapshots (which don't
|
|
|
|
* normally start the data engine).
|
|
|
|
*/
|
|
|
|
private async _withDataEngine(
|
|
|
|
cb: () => Promise<void>,
|
|
|
|
options: {shutdownAfter?: boolean} = {}
|
|
|
|
) {
|
|
|
|
const {shutdownAfter} = options;
|
|
|
|
this._dataEngine = this._dataEngine || this._makeEngine();
|
|
|
|
let engine = await this._dataEngine;
|
|
|
|
if (engine instanceof NullSandbox) {
|
|
|
|
// Make sure the current engine isn't a stub, which may be the case when the
|
|
|
|
// document is a snapshot. Normally, `shutdownAfter` will be true in such
|
|
|
|
// scenarios, so we'll revert back to using a stubbed engine after calling `cb`.
|
|
|
|
this._dataEngine = this._makeEngine();
|
|
|
|
engine = await this._dataEngine;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
await cb();
|
|
|
|
} finally {
|
|
|
|
if (shutdownAfter) {
|
|
|
|
await (await this._dataEngine)?.shutdown();
|
|
|
|
this._dataEngine = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-05-30 12:32:34 +00:00
|
|
|
|
2023-05-23 19:17:28 +00:00
|
|
|
private async _onInactive() {
|
|
|
|
if (Deps.ACTIVEDOC_TIMEOUT_ACTION === 'shutdown') {
|
|
|
|
await this.shutdown();
|
|
|
|
}
|
|
|
|
}
|
2024-01-12 17:35:24 +00:00
|
|
|
|
|
|
|
private _getHomeDbManagerOrFail() {
|
|
|
|
const dbManager = this.getHomeDbManager();
|
|
|
|
if (!dbManager) {
|
|
|
|
throw new Error('HomeDbManager not available');
|
|
|
|
}
|
|
|
|
|
|
|
|
return dbManager;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Helper to initialize a sandbox action bundle with no values.
|
|
|
|
function createEmptySandboxActionBundle(): SandboxActionBundle {
|
|
|
|
return {
|
|
|
|
envelopes: [],
|
|
|
|
stored: [],
|
2021-05-12 15:04:37 +00:00
|
|
|
direct: [],
|
2020-07-21 13:20:51 +00:00
|
|
|
calc: [],
|
|
|
|
undo: [],
|
2022-02-21 14:19:11 +00:00
|
|
|
retValues: [],
|
2022-08-03 07:18:21 +00:00
|
|
|
rowCount: {total: 0},
|
2020-07-21 13:20:51 +00:00
|
|
|
};
|
|
|
|
}
|
2021-10-04 16:14:14 +00:00
|
|
|
|
|
|
|
// Helper that converts a Grist table id to a ref.
|
|
|
|
export function tableIdToRef(metaTables: { [p: string]: TableDataAction }, tableId: string) {
|
|
|
|
const [, , tableRefs, tableData] = metaTables._grist_Tables;
|
|
|
|
const tableRowIndex = tableData.tableId.indexOf(tableId);
|
|
|
|
if (tableRowIndex === -1) {
|
|
|
|
throw new ApiError(`Table not found "${tableId}"`, 404);
|
|
|
|
}
|
|
|
|
return tableRefs[tableRowIndex];
|
|
|
|
}
|
2022-11-15 14:37:48 +00:00
|
|
|
|
2023-03-01 20:43:22 +00:00
|
|
|
// Helper that converts a Grist column colId to a ref given the corresponding table.
|
|
|
|
export function colIdToRef(metaTables: {[p: string]: TableDataAction}, tableId: string, colId: string) {
|
|
|
|
const tableRef = tableIdToRef(metaTables, tableId);
|
|
|
|
|
|
|
|
const [, , colRefs, columnData] = metaTables._grist_Tables_column;
|
|
|
|
const colRowIndex = columnData.colId.findIndex((_, i) => (
|
|
|
|
columnData.colId[i] === colId && columnData.parentId[i] === tableRef
|
|
|
|
));
|
|
|
|
if (colRowIndex === -1) {
|
|
|
|
throw new ApiError(`Column not found "${colId}"`, 404);
|
|
|
|
}
|
|
|
|
return colRefs[colRowIndex];
|
|
|
|
}
|
|
|
|
|
2023-10-12 17:32:22 +00:00
|
|
|
// Helper that check if tableRef is used instead of tableId and return real tableId
|
|
|
|
// If metaTables is not define, activeDoc and req allow it to be created
|
|
|
|
interface MetaTables {
|
|
|
|
metaTables: { [p: string]: TableDataAction }
|
|
|
|
}
|
|
|
|
interface ActiveDocAndReq {
|
|
|
|
activeDoc: ActiveDoc, req: RequestWithLogin
|
|
|
|
}
|
|
|
|
export async function getRealTableId(
|
|
|
|
tableId: string,
|
|
|
|
options: MetaTables | ActiveDocAndReq
|
|
|
|
): Promise<string> {
|
|
|
|
if (parseInt(tableId)) {
|
|
|
|
const metaTables = "metaTables" in options
|
|
|
|
? options.metaTables
|
|
|
|
: await getMetaTables(options.activeDoc, options.req);
|
|
|
|
const [, , tableRefs, tableData] = metaTables._grist_Tables;
|
|
|
|
if (tableRefs.indexOf(parseInt(tableId)) >= 0) {
|
|
|
|
const tableRowIndex = tableRefs.indexOf(parseInt(tableId));
|
|
|
|
return tableData.tableId[tableRowIndex]!.toString();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return tableId;
|
|
|
|
}
|
|
|
|
|
2022-11-15 14:37:48 +00:00
|
|
|
export function sanitizeApplyUAOptions(options?: ApplyUAOptions): ApplyUAOptions {
|
|
|
|
return pick(options||{}, ['desc', 'otherId', 'linkId', 'parseStrings']);
|
|
|
|
}
|