Skip to content

Commit

Permalink
Include waitUntil for activate/install
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiancook committed Dec 1, 2023
1 parent 3ad2fd5 commit 92f1080
Show file tree
Hide file tree
Showing 16 changed files with 103 additions and 25 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ dispatchEvent({
Use this to have the event be dispatched immediately
```javascript
await dispatchEvent({
dispatchEvent({
type: "bingpop",
schedule: {
immediate: true
Expand All @@ -216,7 +216,7 @@ await dispatchEvent({
Use this to have the event be dispatched after a period of time
```javascript
await dispatchEvent({
dispatchEvent({
type: "bingpop",
schedule: {
delay: 1000
Expand All @@ -225,7 +225,7 @@ await dispatchEvent({
```
```javascript
await dispatchEvent({
dispatchEvent({
type: "bingpop",
schedule: {
delay: "1h"
Expand All @@ -238,7 +238,7 @@ await dispatchEvent({
Use this to have the event be dispatched according to a [cron schedule](https://crontab.guru/)
```javascript
await dispatchEvent({
dispatchEvent({
type: "bingpop",
schedule: {
// Triggers at 5am each day
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@
"@virtualstate/impack": "^1.0.0-alpha.8",
"@virtualstate/kdl": "^1.0.1-alpha.29",
"@virtualstate/memo": "^1.8.0",
"@virtualstate/navigation": "^1.0.1-alpha.196",
"@virtualstate/navigation": "^1.0.1-alpha.199",
"@virtualstate/x": "^2.46.0",
"c8": "^7.10.0",
"chance": "^1.1.11",
Expand Down
4 changes: 4 additions & 0 deletions src/fetch/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ export interface WaitUntil {
waitUntil(promise: Promise<void | unknown>): void
}

export interface ExtendableEvent extends WaitUntil, DurableEventData {

}

interface InternalWaitUntil extends WaitUntil {
wait(): Promise<void>;
}
Expand Down
5 changes: 5 additions & 0 deletions src/periodic-sync/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ import {dispatcher} from "../events/schedule/schedule";
import {isLike, ok} from "../is";
import {dispatchSyncEvent, SyncDurableEventData} from "../sync/dispatch";
import {getPeriodicSyncTagRegistrationState, setPeriodicSyncTagRegistrationState} from "./manager";
import {WaitUntil} from "../fetch";

export interface PeriodicSyncDurableEventData extends SyncDurableEventData {
tag: string;
lastChance?: boolean;
}

export interface PeriodicSyncEvent extends PeriodicSyncDurableEventData, WaitUntil {
signal: AbortSignal
}

export function isPeriodicSyncDurableEventData(event: unknown): event is PeriodicSyncDurableEventData {
return !!(
isLike<Partial<PeriodicSyncDurableEventData>>(event) &&
Expand Down
5 changes: 3 additions & 2 deletions src/periodic-sync/virtual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import {DurableEventData, DurableEventSchedule, getDurableEvent, setDurableEvent
import {isMatchingObjects} from "../is";
import {getPeriodicSyncSchedule} from "./schedule";
import {isScheduleRepeating} from "../events/schedule/update";
import {DurablePeriodicSyncManager} from "./manager";

async function * generatePeriodicSyncVirtualEvents() {
const schedules = await getPeriodicSyncSchedule();
async function * generatePeriodicSyncVirtualEvents(manager?: DurablePeriodicSyncManager) {
const schedules = await getPeriodicSyncSchedule(manager);
const type = "periodicsync"
const existingTags = await listDurableEventIds({
type
Expand Down
6 changes: 5 additions & 1 deletion src/sync/dispatch.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {dispatcher, DispatchEventFn} from "../events/schedule/schedule";
import {isLike, isSignalled, ok} from "../is";
import {createWaitUntil} from "../fetch";
import {createWaitUntil, WaitUntil} from "../fetch";
import {DurableEventData} from "../data";
import {
deregisterSyncTag,
Expand All @@ -14,6 +14,10 @@ export interface SyncDurableEventData extends DurableEventData {
lastChance?: boolean;
}

export interface SyncEvent extends SyncDurableEventData, WaitUntil {
signal: AbortSignal
}

export function isSyncDurableEventData(event: unknown): event is SyncDurableEventData {
return !!(
isLike<Partial<SyncDurableEventData>>(event) &&
Expand Down
1 change: 1 addition & 0 deletions src/sync/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export async function deregisterSyncTag(tag: string) {
}

export class DurableSyncManager {

async register(tag: string) {
const store = getSyncTagStore();
const existing = await store.get(tag);
Expand Down
6 changes: 3 additions & 3 deletions src/sync/virtual.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {SyncDurableEventData} from "./dispatch";
import {virtual} from "../events/virtual/virtual";
import {getSyncTagStore} from "./manager";
import {DurableSyncManager, getSyncTagStore} from "./manager";


export async function * generateVirtualSyncEvents(): AsyncIterable<SyncDurableEventData> {
export async function * generateVirtualSyncEvents(manager?: DurableSyncManager): AsyncIterable<SyncDurableEventData> {
const store = getSyncTagStore();
for await (const { tag, lastChance } of store) {
for await (const { tag, lastChance } of manager) {
yield {
// Utilise a durableEventId so that a lock is created per tag
durableEventId: `${store.name}:${tag}`,
Expand Down
8 changes: 8 additions & 0 deletions src/tests/worker/service-worker/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ declare var self: DurableServiceWorkerScope;

console.log("in test service worker");

self.addEventListener("install", event => {
event.waitUntil(Promise.resolve())
});

self.addEventListener("activate", event => {
event.waitUntil(Promise.resolve())
})

self.addEventListener("fetch", event => {
event.respondWith(onFetchEvent(event));
});
Expand Down
14 changes: 11 additions & 3 deletions src/worker/service-worker/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import {virtual} from "../../events/virtual/virtual";
import {isLike, ok} from "../../is";
import {createHash} from "node:crypto";
import {index} from "../../content-index";
import {sync} from "../../sync";
import {DurableSyncManager, sync} from "../../sync";
import {addEventListener} from "../../events/schedule/schedule";
import {dispatchEvent} from "../../events";
import {DurablePeriodicSyncManager} from "../../periodic-sync";

export type DurableServiceWorkerRegistrationState = "pending" | "installing" | "installed" | "activating" | "activated";

Expand Down Expand Up @@ -138,19 +139,26 @@ export class DurableServiceWorkerRegistration {
waiting?: DurableServiceWorker;

index = index;
sync = sync;
sync: DurableSyncManager;
periodicSync: DurablePeriodicSyncManager;

public durable: DurableServiceWorkerRegistrationData;
public readonly isCurrentGlobalScope: boolean;

private unregisterListener;

constructor(data: DurableServiceWorkerRegistrationData,{ isCurrentGlobalScope }: DurableServiceWorkerRegistrationOptions = {}) {
constructor(data: DurableServiceWorkerRegistrationData, { isCurrentGlobalScope }: DurableServiceWorkerRegistrationOptions = {}) {
this.isCurrentGlobalScope = !!isCurrentGlobalScope;
this.#onDurableData(data);
if (this.isCurrentGlobalScope) {
this.unregisterListener = addEventListener(DURABLE_SERVICE_WORKER_REGISTRATION_UPDATE, this.#onDurableDataEvent);
}
this.sync = new DurableSyncManager({

Check failure on line 156 in src/worker/service-worker/container.ts

View workflow job for this annotation

GitHub Actions / test

Expected 0 arguments, but got 1.
serviceWorkerId: data.serviceWorkerId
});
this.periodicSync = new DurablePeriodicSyncManager({

Check failure on line 159 in src/worker/service-worker/container.ts

View workflow job for this annotation

GitHub Actions / test

Expected 0 arguments, but got 1.
serviceWorkerId: data.serviceWorkerId
});
}

#onDurableDataEvent = (event: DurableEvent) => {
Expand Down
5 changes: 1 addition & 4 deletions src/worker/service-worker/default-worker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import { DurableServiceWorkerScope } from "./types";
import "./dispatchers";
import { Push } from "@virtualstate/promise";
import {WORKER_BREAK, WORKER_INITIATED, WORKER_TERMINATE} from "./constants";
import {parentPort, workerData} from "node:worker_threads";
import {onServiceWorkerWorkerData, ServiceWorkerWorkerData} from "./worker";
import { ok } from "../../is";
import {dispatchEvent} from "../../events";
import {DurableEventData} from "../../data";
import {createRespondWith, DurableFetchEventData, isDurableFetchEventData} from "../../fetch";
import {dispatchWorkerEvent} from "./dispatch";

console.log("Default worker!");
Expand Down
18 changes: 18 additions & 0 deletions src/worker/service-worker/dispatchers/activate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {dispatcher} from "../../../events/schedule/schedule";
import {createWaitUntil, ExtendableEvent} from "../../../fetch";

export interface ActivateEvent extends ExtendableEvent {

}

export const removeActivateDispatcher = dispatcher("activate", async (event, dispatch) => {
const {
wait,
waitUntil
} = createWaitUntil(event);
await dispatch({
...event,
waitUntil
});
await wait();
});
2 changes: 2 additions & 0 deletions src/worker/service-worker/dispatchers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./activate";
export * from "./install";
21 changes: 21 additions & 0 deletions src/worker/service-worker/dispatchers/install.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {dispatcher} from "../../../events/schedule/schedule";
import {createWaitUntil, ExtendableEvent} from "../../../fetch";

export interface InstallEvent extends ExtendableEvent {
skipWaiting(): void;
}

export const removeInstallDispatcher = dispatcher("install", async (event, dispatch) => {
const {
wait,
waitUntil
} = createWaitUntil(event);
await dispatch({
...event,
waitUntil,
skipWaiting() {
// TODO noop
}
})
await wait();
});
15 changes: 12 additions & 3 deletions src/worker/service-worker/types.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
import {DurableServiceWorkerRegistration} from "./container";
import {DurableCacheStorage, FetchEvent} from "../../fetch";
import {DurableCacheStorage, ExtendableEvent, FetchEvent} from "../../fetch";
import {DurableContentIndex} from "../../content-index";
import {DurableSyncManager} from "../../sync";
import {SyncEvent} from "../../sync";
import {DurableEventData} from "../../data";
import {PeriodicSyncEvent} from "../../periodic-sync";
import {ActivateEvent, InstallEvent} from "./dispatchers";





export interface DurableServiceWorkerScope {
registration: DurableServiceWorkerRegistration,
caches: DurableCacheStorage,
index: DurableContentIndex,
sync: DurableSyncManager,
serviceWorker: ServiceWorkerContainer
self: DurableServiceWorkerScope,
isSecureContext: boolean
origin: string
addEventListener(type: "fetch", fn: (event: FetchEvent) => void): void;
addEventListener(type: "install", fn: (event: InstallEvent) => void): void;
addEventListener(type: "activate", fn: (event: ActivateEvent) => void): void;
addEventListener(type: "message", fn: (message: MessageEvent) => void): void;
addEventListener(type: "sync", fn: (message: SyncEvent) => void): void;
addEventListener(type: "periodicsync", fn: (message: PeriodicSyncEvent) => void): void;
addEventListener(type: string, fn: (event: DurableEventData) => void): void;
removeEventListener: typeof removeEventListener
}
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4029,10 +4029,10 @@
uuid "^8.3.2"
whatwg-url "^9.1.0"

"@virtualstate/navigation@^1.0.1-alpha.196":
version "1.0.1-alpha.196"
resolved "https://registry.yarnpkg.com/@virtualstate/navigation/-/navigation-1.0.1-alpha.196.tgz#c767538bae4a01f665ab047b7972baa08fbf84fa"
integrity sha512-ovHT29Ec7QaJsgWHKRU2DQ5fX7RHVvPOvKMZOqtjw4uwny4U3K7hfbyjBFUMfGCIxjoYQMmfCUPR/Hn2GY6T9g==
"@virtualstate/navigation@^1.0.1-alpha.199":
version "1.0.1-alpha.199"
resolved "https://registry.yarnpkg.com/@virtualstate/navigation/-/navigation-1.0.1-alpha.199.tgz#68359773ae890cff2cc3125615e4316061256f44"
integrity sha512-CFAtLsq9MgLR96hAMOiQaqaonGCFbOB9I1JM3mO0EpsyF1egD8AzjG+mJWSUBC0KzeBawwbzWDb00SWMGP7uog==
dependencies:
"@ungap/structured-clone" "^1.0.2"
"@virtualstate/composite-key" "^1.0.0"
Expand Down

0 comments on commit 92f1080

Please sign in to comment.