Skip to content

Commit

Permalink
feat(engine): impediment exit hook
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Dec 29, 2023
1 parent d0a45d5 commit 68695a9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
16 changes: 16 additions & 0 deletions packages/engine/src/alwatr-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from '@alwatr/store-types';
import {Dictionary} from '@alwatr/type-helper';
import {waitForTimeout} from '@alwatr/wait';
import exitHook from 'exit-hook'

import {WriteFileMode, existsSync, readJsonFile, resolve, unlink, writeJsonFile} from './lib/node-fs.js';
import {logger} from './logger.js';
Expand Down Expand Up @@ -89,6 +90,7 @@ export class AlwatrStore {
logger.logMethodArgs?.('new', config__);
this.config__.defaultChangeDebounce ??= 40;
this.rootDb__ = this.loadRootDb__();
exitHook(this.exitHook__.bind(this));
}

/**
Expand Down Expand Up @@ -357,4 +359,18 @@ export class AlwatrStore {
const context = readJsonFile(fullPath, true) as CollectionContext<StoreFileStat>;
return CollectionReference.newRefFromContext(context, this.storeChanged__.bind(this), 'root-db');
}

/**
* Save all store files.
*/
private exitHook__(): void {
logger.logMethod?.('exitHook__');
for (const ref of Object.values(this.cacheReferences__)) {
if (ref.hasUnprocessedChanges_ === true) {
ref.hasUnprocessedChanges_ = false;
logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});
writeJsonFile(resolve(this.config__.rootPath, ref.path), ref.getFullContext_(), WriteFileMode.Rename, true);
}
}
}
}
11 changes: 10 additions & 1 deletion packages/reference/src/collection-reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,11 @@ export class CollectionReference<TItem extends Dictionary = Dictionary> {
*/
readonly path: string;

/**
* Indicates whether the collection has unsaved changes.
*/
hasUnprocessedChanges_ = false;

/**
* Logger instance for this collection.
*/
Expand Down Expand Up @@ -483,6 +488,7 @@ export class CollectionReference<TItem extends Dictionary = Dictionary> {
*/
private async updated__(id?: string | number): Promise<void> {
this.logger__.logMethodArgs?.('updated__', {delayed: this.updateDelayed__});
this.hasUnprocessedChanges_ = true;
this.updateMeta__(id);

if (this.updateDelayed__ === true) return;
Expand All @@ -494,7 +500,10 @@ export class CollectionReference<TItem extends Dictionary = Dictionary> {
this.updateDelayed__ = false;
}

this.updatedCallback__.call(null, this);
if (this.hasUnprocessedChanges_ === true) {
this.hasUnprocessedChanges_ = false;
this.updatedCallback__.call(null, this);
}
}

/**
Expand Down

0 comments on commit 68695a9

Please sign in to comment.