Skip to content

Commit 14bec95

Browse files
committed
database: decaff blobs related methods
1 parent e224aa8 commit 14bec95

File tree

10 files changed

+2408
-782
lines changed

10 files changed

+2408
-782
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ go
2626

2727
src/cocalc-testcafe/package-lock.json
2828

29+
src/packages/database/coverage/
30+
2931
src/tsconfig.tsbuildinfo
3032

3133
src/static/

src/packages/database/DB_DEVELOPMENT.md

Lines changed: 225 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,26 @@
77

88
## Current Status
99

10-
**Migration Progress: 35% Complete (2,393 of 6,827 lines)**
10+
**Migration Progress: 46% Complete (3,154 of 6,827 lines)**
1111

1212
### Remaining CoffeeScript Files
1313

1414
| File | Lines | Description | Priority |
1515
| -------------------------------- | ----- | ----------------------------------------------- | ------------ |
1616
| `postgres-server-queries.coffee` | 2,518 | Server-side database queries | High |
1717
| `postgres-base.coffee` | 1,156 | Core PostgreSQL class and connection management | **Critical** |
18-
| `postgres-blobs.coffee` | 760 | Blob storage operations | Medium |
19-
| **Total Remaining** | 4,434 | | |
18+
| **Total Remaining** | 3,674 | | |
2019

2120
### Completed Migrations ✅
2221

23-
| File | Lines | Migrated To | Tests | Status |
24-
| ------------------------------ | ----- | -------------------------- | ----- | ---------- |
25-
| `postgres-user-queries.coffee` | 1,790 | `user-query/queries.ts` | 150 | ✅ Removed |
26-
| `postgres-synctable.coffee` | 604 | `synctable/*.ts` (3 files) | 109 | ✅ Removed |
27-
| **Total Migrated** | 2,394 | **35% of original code** | 259 | |
22+
| File | Lines | Migrated To | Tests | Status |
23+
| ------------------------------ | ----- | ------------------------------- | ----- | ---------- |
24+
| `postgres-user-queries.coffee` | 1,790 | `user-query/queries.ts` | 150 | ✅ Removed |
25+
| `postgres-synctable.coffee` | 604 | `synctable/*.ts` (3 files) | 109 | ✅ Removed |
26+
| `postgres-blobs.coffee` | 760 | `postgres/blobs/*.ts` (3 files) | 42 | ✅ Removed |
27+
| **Total Migrated** | 3,154 | **46% of original code** | 301 | |
2828

29-
**All database tests passing: 328/328**
29+
**All database tests passing: 374/374**
3030

3131
## Architecture Overview
3232

@@ -40,7 +40,7 @@ export function db(opts = {}): PostgreSQL {
4040
let PostgreSQL = base.PostgreSQL;
4141

4242
PostgreSQL = postgresServerQueries.extend_PostgreSQL(PostgreSQL);
43-
PostgreSQL = postgresBlobs.extend_PostgreSQL(PostgreSQL);
43+
PostgreSQL = extendPostgresBlobs(PostgreSQL); // ✅ TypeScript
4444
PostgreSQL = extendPostgresSynctable(PostgreSQL); // ✅ TypeScript
4545
PostgreSQL = extendPostgresUserQueries(PostgreSQL); // ✅ TypeScript
4646
PostgreSQL = extendPostgresOps(PostgreSQL); // ✅ TypeScript
@@ -204,6 +204,221 @@ Key features:
204204
- Reference-counted trigger registration
205205
- Reconnection handling with state preservation
206206

207+
### ✅ postgres-blobs.coffee → postgres/blobs/ (3 files)
208+
209+
**Migrated**: December 2024
210+
**Complexity**: Medium - Blob storage with compression and external storage integration
211+
**Tests**: 42 comprehensive tests (100% pass rate)
212+
**Result**: Split into 3 TypeScript modules, CoffeeScript file removed
213+
214+
**File structure:**
215+
216+
- `postgres/blobs/methods.ts` - Main blob storage methods (1,070 lines, 14 methods)
217+
- `postgres/blobs/archive.ts` - Patch archiving functions (`archivePatches`, `exportPatches`)
218+
- `postgres/blobs/index.ts` - Extension module export
219+
220+
Key methods migrated:
221+
222+
- **Blob Operations**: `save_blob`, `get_blob`, `delete_blob`, `touch_blob`, `remove_blob_ttls`
223+
- **External Storage**: `copy_blob_to_gcloud`, `copy_all_blobs_to_gcloud`, `blob_store`, `close_blob`
224+
- **Maintenance**: `backup_blobs_to_tarball`, `blob_maintenance`, `syncstring_maintenance`
225+
- **Patch Management**: `archivePatches`, `export_patches`, `import_patches`
226+
227+
Key features:
228+
229+
- Compression support (gzip, zlib) with configurable levels
230+
- TTL (time-to-live) management with automatic expiration
231+
- External storage integration (Google Cloud Storage via filesystem buckets)
232+
- Blob verification with SHA1 UUID checking
233+
- Batch operations with throttling and retry logic
234+
- Incremental backup to tarballs
235+
236+
**Migration notes:**
237+
238+
- Fixed spread operator issue in `archivePatches` using `Object.assign` for decaffeinate compatibility
239+
- Used `bind_methods(this)` utility instead of 17 individual method bindings
240+
- Added proper TypeScript type annotations for all variables and parameters
241+
- All async operations properly handled with async/await pattern
242+
- Tests cover compression, TTL, metadata, external storage, and maintenance operations
243+
244+
## Remaining CoffeeScript Files - Detailed Analysis
245+
246+
### Already Extracted to TypeScript
247+
248+
The migration has made significant progress beyond the completed files. **49+ TypeScript modules** have been extracted from the remaining CoffeeScript files:
249+
250+
#### Core modules (`postgres/` - 29 files)
251+
252+
- `account-queries.ts` - Account management and payment status
253+
- `always-running.ts` - Always-running project detection
254+
- `central-log.ts` - Central logging system
255+
- `changefeed.ts`, `changefeed-query.ts` - Real-time changefeeds
256+
- `delete-patches.ts`, `delete-projects.ts` - Cleanup operations
257+
- `passport.ts`, `passport-store.ts` - SSO authentication
258+
- `project-queries.ts` - Project datastore operations
259+
- `public-paths.ts` - Public path management
260+
- `remember-me.ts` - Session management
261+
- `registration-tokens.ts` - User registration tokens
262+
- `stats.ts` - Analytics and statistics
263+
- `user-tracking.ts` - User activity tracking
264+
- `query.ts`, `util.ts`, `types.ts` - Query helpers and types
265+
- `record-connect-error.ts` - Connection error tracking
266+
- `server-settings.ts` - Server configuration
267+
- `set-pg-params.ts` - PostgreSQL parameter configuration
268+
- `messages.ts`, `news.ts`, `personal.ts`, `pii.ts` - Various features
269+
270+
#### Specialized subdirectories (20+ files)
271+
272+
- **`postgres/blobs/`** (3 files) - ✅ Blob storage with compression and external storage (fully migrated!)
273+
- **`postgres/schema/`** (8 files) - Schema management, pg-type conversion, table sync, indexes
274+
- **`postgres/ops/`** (4 files) - ✅ Backup/restore operations (fully TypeScript!)
275+
- **`postgres/site-license/`** (8 files) - License analytics, usage logs, public info, manager, search
276+
- **`postgres/stripe/`** (3 files) - Payment processing, customer sync
277+
- **`synctable/`** (3 files) - ✅ Real-time table synchronization (fully migrated!)
278+
- **`user-query/`** (3+ files) - ✅ User query system (fully migrated!)
279+
280+
### 1. postgres-base.coffee (1,156 lines) - **CRITICAL PRIORITY**
281+
282+
**Status**: Foundation class - contains core functionality that cannot be easily extracted
283+
284+
**~38 methods** including:
285+
286+
**Connection Management:**
287+
288+
- `connect`, `disconnect`, `_connect` - Connection pooling with retry logic
289+
- `is_connected` - Connection status check
290+
- Multi-host DNS resolution and failover
291+
- Connection health monitoring with automatic reconnection
292+
293+
**Query Engine:**
294+
295+
- `_query`, `_do_query` - Core query execution with timeout handling
296+
- `_client` - Get PostgreSQL client from pool
297+
- Query result caching (LRU cache)
298+
- Concurrent query tracking and load management
299+
300+
**LISTEN/NOTIFY Infrastructure:**
301+
302+
- `_listen`, `_stop_listening` - PostgreSQL NOTIFY subscription
303+
- `_notification` - Notification handler
304+
- `_listening`, `_clear_listening_state` - State management
305+
306+
**Schema Helpers:**
307+
308+
- `_primary_key`, `_primary_keys` - Primary key lookup from schema
309+
- Database existence checking (`_ensure_database_exists`)
310+
311+
**Other:**
312+
313+
- `_dbg` - Debug logging helper
314+
- `concurrent` - Query concurrency tracking
315+
- `_init_metrics`, metrics tracking
316+
- `close`, `clear_cache`, `engine`
317+
318+
**Complexity**: Very High - This is the foundation that all other modules depend on
319+
320+
**Migration Strategy**: Requires comprehensive test coverage before migration. Consider incremental approach:
321+
322+
1. Write extensive tests for all core functionality
323+
2. Extract query caching logic first
324+
3. Extract connection health monitoring
325+
4. Extract LISTEN/NOTIFY infrastructure
326+
5. Finally migrate core PostgreSQL class constructor and connection pool
327+
328+
### 2. postgres-server-queries.coffee (2,518 lines) - **HIGH PRIORITY**
329+
330+
**Status**: Orchestrator file - **Most methods already delegate to TypeScript modules**
331+
332+
**~128 methods**, with extensive imports from TypeScript modules:
333+
334+
```coffeescript
335+
# Already using TypeScript modules:
336+
{get_remember_me} = require('./postgres/remember-me')
337+
{is_paying_customer} = require('./postgres/account-queries')
338+
{getStripeCustomerId, syncCustomer} = require('./postgres/stripe')
339+
{site_license_usage_stats, ...} = require('./postgres/site-license/analytics')
340+
{permanently_unlink_all_deleted_projects_of_user} = require('./postgres/delete-projects')
341+
{get_all_public_paths, unlist_all_public_paths} = require('./postgres/public-paths')
342+
{get_personal_user} = require('./postgres/personal')
343+
{passport functions} = require('./postgres/passport')
344+
{projects_that_need_to_be_started} = require('./postgres/always-running')
345+
{calc_stats} = require('./postgres/stats')
346+
{pii_expire} = require('./postgres/pii')
347+
{updateUnreadMessageCount} = require('./postgres/messages')
348+
centralLog = require('./postgres/central-log')
349+
# ...and more
350+
```
351+
352+
**Method Categories:**
353+
354+
- **Central Logging**: `log`, `get_log`, `uncaught_exception` - use `central-log.ts`
355+
- **Account Management**: Uses `account-queries.ts` for payment status, user info
356+
- **Stripe Integration**: Uses `postgres/stripe/*.ts` for payment processing
357+
- **Site Licenses**: Uses `postgres/site-license/*.ts` (8 TypeScript modules)
358+
- **Project Operations**: Uses `project-queries.ts`, `delete-projects.ts`, `always-running.ts`
359+
- **Authentication**: Uses `passport.ts`, `registration-tokens.ts`, `remember-me.ts`
360+
- **User Tracking**: Uses `user-tracking.ts`, `messages.ts`, `personal.ts`
361+
- **Server Settings**: Configuration and passport caching
362+
- **Statistics**: Uses `stats.ts`
363+
364+
**Complexity**: Medium - Mostly orchestration and wrapping existing TypeScript functions
365+
366+
**Migration Strategy**: This file is a good candidate for next migration:
367+
368+
1. Identify remaining methods that haven't been extracted
369+
2. Convert wrapper methods to TypeScript extend pattern
370+
3. Create `postgres/server-queries/` directory for remaining implementations
371+
4. Most functionality already tested through extracted modules
372+
373+
## Migration Recommendations
374+
375+
### Recommended Migration Order
376+
377+
Based on complexity, dependencies, and risk:
378+
379+
**Phase 2A: ✅ postgres-blobs.coffee → postgres/blobs/ (COMPLETED)**
380+
381+
- **Status**: ✅ Migrated December 2024
382+
- **Result**: 3 TypeScript files, 42 tests, CoffeeScript file removed
383+
- **Lessons learned**: Spread operator required Object.assign workaround for decaffeinate
384+
385+
**Phase 2B: postgres-server-queries.coffee → postgres/server-queries/ (RECOMMENDED NEXT)**
386+
387+
- **Effort**: Medium-High (2,518 lines, 128 methods)
388+
- **Risk**: Medium - Many methods but most delegate to TypeScript modules
389+
- **Already extracted**: Most functionality in 20+ TypeScript modules
390+
- **Remaining work**: Convert orchestration/wrapper methods, identify non-extracted methods
391+
- **Strategy**: Incremental migration - group related methods and migrate in batches
392+
393+
**Phase 2C: postgres-base.coffee → postgres/base.ts**
394+
395+
- **Effort**: High (1,156 lines, 38 methods)
396+
- **Risk**: **CRITICAL** - Foundation class for all database operations
397+
- **Dependencies**: Everything depends on this
398+
- **Remaining work**: Connection pooling, query engine, LISTEN/NOTIFY, schema helpers
399+
- **Prerequisites**: Comprehensive test coverage required before starting
400+
- **Strategy**: Extract incrementally - start with query caching, then connection health, then LISTEN/NOTIFY
401+
402+
### Next Steps
403+
404+
1. **Immediate**: Analyze `postgres-server-queries.coffee` in detail
405+
- Identify which methods still need extraction (vs. already delegating)
406+
- Create migration plan for remaining methods
407+
- Group related methods for incremental migration
408+
- Target: Migrate in 3-4 batches to reduce risk
409+
410+
2. **Short-term**: Begin `postgres-server-queries.coffee` migration
411+
- Start with highest-value or most isolated method groups
412+
- Write tests for any untested methods
413+
- Migrate batch by batch, verifying tests after each batch
414+
- Update documentation after each batch
415+
416+
3. **Medium-term**: Plan `postgres-base.coffee` migration
417+
- Write extensive integration tests for core functionality
418+
- Consider incremental extraction approach
419+
- This is the most critical migration and requires careful planning
420+
- May require coordination with CoCalc deployment team
421+
207422
## Resources
208423

209424
- [decaffeinate Documentation](https://github.com/decaffeinate/decaffeinate)

src/packages/database/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ import { PostgreSQL } from "./postgres/types";
1717

1818
const base = require("./postgres-base");
1919
const postgresServerQueries = require("./postgres-server-queries");
20-
const postgresBlobs = require("./postgres-blobs");
20+
// Migrated to TypeScript: postgres/blobs/methods.ts
21+
import { extend_PostgreSQL as extendPostgresBlobs } from "./postgres/blobs";
2122
// Migrated to TypeScript: user-query/queries.ts
2223
import { extend_PostgreSQL as extendPostgresUserQueries } from "./user-query/queries";
2324
// Migrated to TypeScript: synctable/methods.ts
@@ -44,7 +45,7 @@ export function db(opts = {}): PostgreSQL {
4445
let PostgreSQL = base.PostgreSQL;
4546

4647
PostgreSQL = postgresServerQueries.extend_PostgreSQL(PostgreSQL);
47-
PostgreSQL = postgresBlobs.extend_PostgreSQL(PostgreSQL);
48+
PostgreSQL = extendPostgresBlobs(PostgreSQL);
4849
PostgreSQL = extendPostgresSynctable(PostgreSQL);
4950
PostgreSQL = extendPostgresUserQueries(PostgreSQL);
5051
PostgreSQL = extendPostgresOps(PostgreSQL);

0 commit comments

Comments
 (0)