@octane-xplat/background-tasks 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,52 +1,5 @@
1
1
  # @octane-xplat/background-tasks
2
2
 
3
- Define deferrable work for iOS/Android scheduler experiments. The OS chooses
4
- when work runs; this is not an exact timer. The current Android cold-start/
5
- completion bridge and iOS outcome/expiration/recurrence lifecycle have open
6
- gaps ([#71](https://github.com/octane-xplat/octane-xplat/issues/71),
7
- [#72](https://github.com/octane-xplat/octane-xplat/issues/72)). Do not treat
8
- registration as a production delivery guarantee. Web/desktop are unsupported.
3
+ [Documentation](https://octane-xplat.goddardai.org/package-background-tasks).
9
4
 
10
- Follow [Run a background refresh](https://octane-xplat.goddardai.org/background-work)
11
- for a maintained timestamp job, foreground recovery screen, native configuration,
12
- launch-time registration, disable and execution checks.
13
-
14
- ## Define a small task
15
-
16
- Install in an existing Xplat app:
17
-
18
- ```sh
19
- bun add @octane-xplat/background-tasks @octane-xplat/platform
20
- ```
21
-
22
- Define tasks at module scope in a module imported at native startup. Keep their
23
- results outside mounted screens, and confirm durable writes. This definition
24
- records an execution attempt; it does not itself schedule or prove OS delivery:
25
-
26
- ```ts
27
- import { backgroundTasks } from '@octane-xplat/background-tasks'
28
- import { storage } from '@octane-xplat/platform'
29
-
30
- backgroundTasks.defineTask('record-refresh', async () => {
31
- try {
32
- storage.setString('refresh.background-at', new Date().toISOString())
33
- return storage.flush() ? 'success' : 'failed'
34
- } catch {
35
- return 'failed'
36
- }
37
- })
38
- ```
39
-
40
- Use the guide's [native configuration](https://octane-xplat.goddardai.org/background-work#configure-the-native-experiment)
41
- and [startup request](https://octane-xplat.goddardai.org/background-work#request-once-at-startup)
42
- before scheduling. On iOS, the task requires a permitted full identifier and a
43
- handler registered once before app launch finishes. Repeated registration can
44
- terminate the app; do not register from a button or hot-reloaded component.
45
- Android carries a WorkManager bridge with a 15-minute interval floor, but its
46
- current worker does not bootstrap a dead JS runtime.
47
-
48
- Keep the [foreground fallback](https://octane-xplat.goddardai.org/background-work#disable-retry-and-fall-back).
49
- The interval is in seconds and is a scheduling hint. `isRegistered` only checks
50
- the current JS map, not the OS queue. Qualify a persisted execution timestamp,
51
- actual task outcome and subsequent delivery using the guide's
52
- [device procedure](https://octane-xplat.goddardai.org/background-work#prove-execution-separately).
5
+ [API reference](https://octane-xplat.goddardai.org/api-background-tasks).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octane-xplat/background-tasks",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "OS-scheduled periodic background work for Octane xplat — BGTaskScheduler and WorkManager",
5
5
  "keywords": [
6
6
  "android",
@@ -48,7 +48,7 @@
48
48
  "access": "public"
49
49
  },
50
50
  "scripts": {
51
- "test": "node --test tests/*.test.ts",
51
+ "test": "node --test tests/*.test.ts tests/*.test.mjs",
52
52
  "typegen": "tsrx-typegen --target octane",
53
53
  "prepack": "bun run typegen && tsrx-typegen --pack-check",
54
54
  "pack:check": "tsrx-typegen --pack-check",
@@ -58,10 +58,11 @@
58
58
  "@nativescript-community/octane": "0.2.5",
59
59
  "@nativescript/core": "9.1.3",
60
60
  "@nativescript/types": "9.1.4",
61
- "@tsrx/typescript-plugin": "0.4.11",
62
61
  "octane": "0.16.3",
63
- "tsrx-typegen": "0.5.0",
64
- "typescript": "5.9.3"
62
+ "tsrx-typegen": "0.6.1",
63
+ "typescript": "7.1.0-beta",
64
+ "@tsrx/content-mapper": "0.1.2",
65
+ "typescript-classic": "npm:typescript@5.9.3"
65
66
  },
66
67
  "peerDependencies": {
67
68
  "@nativescript-community/octane": ">=0.2.1 <1",
@@ -83,6 +84,6 @@
83
84
  }
84
85
  },
85
86
  "dependencies": {
86
- "@octane-xplat/platform": "0.19.0"
87
+ "@octane-xplat/platform": "0.20.0"
87
88
  }
88
89
  }
@@ -2,24 +2,19 @@ package com.octanexplat.tasks;
2
2
 
3
3
  import android.content.Context;
4
4
  import androidx.work.*;
5
- import com.tns.Utils;
6
5
  import java.util.concurrent.TimeUnit;
7
6
 
8
7
  public class TaskScheduler {
9
- public static void schedule(String name, long intervalSeconds) {
8
+ public static void schedule(Context context, String name, long intervalSeconds) {
10
9
  long interval = Math.max(intervalSeconds, 15 * 60); // WorkManager floor
11
10
  PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(TaskWorker.class, interval, TimeUnit.SECONDS)
12
11
  .addTag("xplat:" + name)
13
12
  .build();
14
- WorkManager.getInstance(context())
13
+ WorkManager.getInstance(context.getApplicationContext())
15
14
  .enqueueUniquePeriodicWork("xplat:" + name, ExistingPeriodicWorkPolicy.UPDATE, request);
16
15
  }
17
16
 
18
- public static void cancel(String name) {
19
- WorkManager.getInstance(context()).cancelUniqueWork("xplat:" + name);
20
- }
21
-
22
- private static Context context() {
23
- return Utils.getApplicationContext();
17
+ public static void cancel(Context context, String name) {
18
+ WorkManager.getInstance(context.getApplicationContext()).cancelUniqueWork("xplat:" + name);
24
19
  }
25
20
  }
@@ -3,8 +3,49 @@ package com.octanexplat.tasks;
3
3
  import android.content.Context;
4
4
  import androidx.work.*;
5
5
  import com.tns.Runtime;
6
+ import java.util.concurrent.CountDownLatch;
7
+ import java.util.concurrent.TimeUnit;
6
8
 
7
9
  public class TaskWorker extends Worker {
10
+ private static final long RESULT_TIMEOUT_MS = 25_000;
11
+
12
+ // Implemented by the JS module. Calls dispatched from Java run on the JS
13
+ // thread through the NativeScript proxy and block until it returns.
14
+ public interface TaskRunner {
15
+ void run(String name, TaskOutcome outcome);
16
+ }
17
+
18
+ // The JS side reports the executor's settled result through onResult;
19
+ // the first report wins and releases the waiting worker thread.
20
+ public static class TaskOutcome {
21
+ private final CountDownLatch done = new CountDownLatch(1);
22
+ private volatile String result = "failed";
23
+
24
+ public void onResult(String value) {
25
+ if (done.getCount() == 0) {
26
+ return;
27
+ }
28
+ result = value == null ? "failed" : value;
29
+ done.countDown();
30
+ }
31
+
32
+ String result() {
33
+ return result;
34
+ }
35
+
36
+ boolean await() throws InterruptedException {
37
+ return done.await(RESULT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
38
+ }
39
+ }
40
+
41
+ private static volatile TaskRunner runner;
42
+
43
+ // The JS module registers its runner at evaluation time — the supported
44
+ // Java→JS bridge needs a JS-implemented object, not a global function.
45
+ public static void setTaskRunner(TaskRunner taskRunner) {
46
+ runner = taskRunner;
47
+ }
48
+
8
49
  public TaskWorker(Context context, WorkerParameters params) {
9
50
  super(context, params);
10
51
  }
@@ -19,32 +60,29 @@ public class TaskWorker extends Worker {
19
60
  if (name == null) {
20
61
  return Result.failure();
21
62
  }
22
- Runtime runtime = Runtime.getCurrentRuntime();
23
- if (runtime == null) {
63
+ if (Runtime.getCurrentRuntime() == null) {
24
64
  // Cold start: the runtime isn't up — WorkManager retry re-runs us.
25
65
  return Result.retry();
26
66
  }
27
- final boolean[] done = { false };
28
- final boolean[] ok = { false };
29
- runtime.runOnJSThread(() -> {
30
- try {
31
- Object fn = ((com.tns.Runtime) runtime).callJSMethod(
32
- com.tns.Runtime.getCurrentRuntime(),
33
- "global.__xplatBackgroundTaskRun",
34
- Object.class,
35
- name,
36
- (com.tns.CompletionListener) null);
37
- ok[0] = !"failed".equals(String.valueOf(fn));
38
- } catch (Throwable ignored) {
39
- } finally {
40
- done[0] = true;
67
+ TaskRunner taskRunner = runner;
68
+ if (taskRunner == null) {
69
+ // Warm runtime whose module evaluation never registered a runner.
70
+ return Result.retry();
71
+ }
72
+ TaskOutcome outcome = new TaskOutcome();
73
+ try {
74
+ taskRunner.run(name, outcome);
75
+ } catch (Throwable t) {
76
+ return Result.retry();
77
+ }
78
+ try {
79
+ if (!outcome.await()) {
80
+ return Result.retry();
41
81
  }
42
- });
43
- long waited = 0;
44
- while (!done[0] && waited < 25_000) {
45
- try { Thread.sleep(50); } catch (InterruptedException e) { break; }
46
- waited += 50;
82
+ } catch (InterruptedException e) {
83
+ Thread.currentThread().interrupt();
84
+ return Result.retry();
47
85
  }
48
- return ok[0] ? Result.success() : Result.retry();
86
+ return "success".equals(outcome.result()) ? Result.success() : Result.retry();
49
87
  }
50
88
  }
@@ -3,14 +3,14 @@
3
3
  import type { BackgroundTasks, TaskStatus } from './types'
4
4
 
5
5
  const unsupported = () =>
6
- Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
6
+ Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
7
7
 
8
8
  /** Background-task scheduler service — see BackgroundTasks for the contract. */
9
9
  export const backgroundTasks: BackgroundTasks = {
10
- supported: false,
11
- defineTask: () => {},
12
- register: unsupported,
13
- unregister: unsupported,
14
- getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
- isRegistered: async () => false,
10
+ supported: false,
11
+ defineTask: () => {},
12
+ register: unsupported,
13
+ unregister: unsupported,
14
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
+ isRegistered: async () => false,
16
16
  }
@@ -13,70 +13,77 @@ const executors = new Map<string, TaskExecutor>()
13
13
  const schedulers = new Map<string, any>()
14
14
 
15
15
  const schedulerClass = (): any => {
16
- try {
17
- return typeof NSBackgroundActivityScheduler?.alloc === 'function'
18
- ? NSBackgroundActivityScheduler
19
- : null
20
- } catch {
21
- return null
22
- }
16
+ try {
17
+ return typeof NSBackgroundActivityScheduler?.alloc === 'function'
18
+ ? NSBackgroundActivityScheduler
19
+ : null
20
+ } catch {
21
+ return null
22
+ }
23
23
  }
24
24
 
25
25
  /** Background-task scheduler service — see BackgroundTasks for the contract. */
26
26
  export const backgroundTasks: BackgroundTasks = {
27
- get supported() {
28
- return schedulerClass() !== null
29
- },
30
-
31
- defineTask(name: string, executor: TaskExecutor): void {
32
- executors.set(name, executor)
33
- },
34
-
35
- register: async (name: string, options?: { minimumInterval?: number }): Promise<void> => {
36
- if (!executors.has(name)) {
37
- throw new Error(`backgroundTasks.register: no task defined as '${name}'`)
38
- }
39
-
40
- const klass = schedulerClass()
41
- if (!klass) {
42
- throw new Error('backgroundTasks.register: NSBackgroundActivityScheduler is unavailable')
43
- }
44
-
45
- backgroundTasks.unregister(name).catch(() => {})
46
- const scheduler = klass.alloc().initWithIdentifier(`xplat.background.${name}`)
47
- scheduler.repeats = true
48
- scheduler.interval = Math.max(options?.minimumInterval ?? 3600, 60)
49
- scheduler.tolerance = scheduler.interval / 2
50
- scheduler.qualityOfService = 0x09 // NSQualityOfServiceBackground
51
- scheduler.scheduleWithBlock((completion: (result: number) => void) => {
52
- const executor = executors.get(name)
53
- if (scheduler.shouldDefer || !executor) {
54
- completion(RESULT_DEFERRED)
55
- return
56
- }
57
-
58
- Promise.resolve()
59
- .then(() => executor({ name }))
60
- .then((result: TaskResult) => completion(result === 'success' ? RESULT_FINISHED : RESULT_DEFERRED))
61
- .catch(() => completion(RESULT_DEFERRED))
62
- })
63
- schedulers.set(name, scheduler)
64
- },
65
-
66
- unregister: async (name: string): Promise<void> => {
67
- const scheduler = schedulers.get(name)
68
- if (scheduler) {
69
- schedulers.delete(name)
70
- try {
71
- scheduler.invalidate()
72
- } catch {
73
- // Invalidating a released scheduler must not poison unregister.
74
- }
75
- }
76
- },
77
-
78
- getStatus: async (): Promise<TaskStatus> =>
79
- schedulerClass() ? 'available' : 'unavailable',
80
-
81
- isRegistered: async (name: string): Promise<boolean> => schedulers.has(name),
27
+ get supported() {
28
+ return schedulerClass() !== null
29
+ },
30
+
31
+ defineTask(name: string, executor: TaskExecutor): void {
32
+ executors.set(name, executor)
33
+ },
34
+
35
+ register: async (name: string, options?: { minimumInterval?: number }): Promise<void> => {
36
+ if (!executors.has(name)) {
37
+ throw new Error(`backgroundTasks.register: no task defined as '${name}'`)
38
+ }
39
+
40
+ const klass = schedulerClass()
41
+
42
+ if (!klass) {
43
+ throw new Error('backgroundTasks.register: NSBackgroundActivityScheduler is unavailable')
44
+ }
45
+
46
+ backgroundTasks.unregister(name).catch(() => {})
47
+
48
+ const scheduler = klass.alloc().initWithIdentifier(`xplat.background.${name}`)
49
+
50
+ scheduler.repeats = true
51
+ scheduler.interval = Math.max(options?.minimumInterval ?? 3600, 60)
52
+ scheduler.tolerance = scheduler.interval / 2
53
+ scheduler.qualityOfService = 0x09 // NSQualityOfServiceBackground
54
+ scheduler.scheduleWithBlock((completion: (result: number) => void) => {
55
+ const executor = executors.get(name)
56
+
57
+ if (scheduler.shouldDefer || !executor) {
58
+ completion(RESULT_DEFERRED)
59
+ return
60
+ }
61
+
62
+ Promise.resolve()
63
+ .then(() => executor({ name, expired: false }))
64
+ .then((result: TaskResult) =>
65
+ completion(result === 'success' ? RESULT_FINISHED : RESULT_DEFERRED),
66
+ )
67
+ .catch(() => completion(RESULT_DEFERRED))
68
+ })
69
+
70
+ schedulers.set(name, scheduler)
71
+ },
72
+
73
+ unregister: async (name: string): Promise<void> => {
74
+ const scheduler = schedulers.get(name)
75
+
76
+ if (scheduler) {
77
+ schedulers.delete(name)
78
+ try {
79
+ scheduler.invalidate()
80
+ } catch {
81
+ // Invalidating a released scheduler must not poison unregister.
82
+ }
83
+ }
84
+ },
85
+
86
+ getStatus: async (): Promise<TaskStatus> => (schedulerClass() ? 'available' : 'unavailable'),
87
+
88
+ isRegistered: async (name: string): Promise<boolean> => schedulers.has(name),
82
89
  }
@@ -1,129 +1,260 @@
1
1
  // Background tasks — native leaf, custom bridge (no NS plugin exists).
2
2
  // iOS: BGTaskScheduler app-refresh requests; the Info.plist registers the
3
3
  // task identifier and UIBackgroundModes fetch. Android: WorkManager periodic
4
- // requests through platforms/android Gradle deps; the Worker spins up the
5
- // runtime and calls back into __xplatBackgroundTaskRun.
4
+ // requests through platforms/android Gradle deps; the Worker dispatches to
5
+ // the TaskRunner registered below while a runtime is warm.
6
6
  //
7
7
  // defineTask bodies must be registered at module scope — the OS can invoke a
8
8
  // task before app code runs again, and a relaunch only re-evaluates module
9
- // top-level. expo-task-manager's constraint, mirrored deliberately.
10
- import { Application, Utils, isIOS } from '@nativescript/core'
11
- import type { BackgroundTasks, TaskExecutor, TaskResult, TaskStatus } from './types'
9
+ // top-level. That placement is also Apple's registration window: launch
10
+ // handlers must be registered before app launch finishes, and a second
11
+ // registration of the same identifier kills the app. defineTask therefore
12
+ // owns iOS handler registration (once per identifier); register/unregister
13
+ // only submit or cancel refresh requests and are safe to repeat.
14
+ import { isIOS, Utils } from '@nativescript/core'
15
+ import type { BackgroundTasks, TaskContext, TaskExecutor, TaskResult, TaskStatus } from './types'
12
16
 
13
17
  declare const BGTaskScheduler: any
14
18
  declare const BGAppRefreshTaskRequest: any
19
+ declare const interop: any
15
20
 
16
21
  const executors = new Map<string, TaskExecutor>()
17
22
  const registered = new Map<string, number>()
23
+ const handledIdentifiers = new Set<string>()
24
+ const handlerReady = new Set<string>()
18
25
 
19
26
  const TASK_PREFIX = 'com.octanexplat.tasks.'
20
27
 
21
- async function runTask(name: string): Promise<TaskResult> {
22
- const executor = executors.get(name)
23
- if (!executor) {
24
- return 'failed'
25
- }
26
- try {
27
- return (await executor({ name })) ?? 'success'
28
- } catch {
29
- return 'failed'
30
- }
28
+ async function runTask(name: string, context: TaskContext): Promise<TaskResult> {
29
+ const executor = executors.get(name)
30
+
31
+ if (!executor) {
32
+ return 'failed'
33
+ }
34
+
35
+ try {
36
+ return (await executor(context)) ?? 'success'
37
+ } catch {
38
+ return 'failed'
39
+ }
40
+ }
41
+
42
+ // iOS: submit (or replace) the pending refresh request for a task. Each
43
+ // request is consumed by one run, so enable/reschedule and the post-run
44
+ // resubmission share this path. Cancelling first keeps repeated calls
45
+ // idempotent — submitting over a pending request can fail with
46
+ // BGTaskSchedulerErrorCodeTooManyPendingTaskRequests. Submitting without a
47
+ // registered launch handler is not a soft failure: BGTaskScheduler raises an
48
+ // uncatchable NSInternalInconsistencyException that kills the process, so the
49
+ // ready check is a hard gate.
50
+ function iosSubmit(name: string): void {
51
+ const identifier = TASK_PREFIX + name
52
+
53
+ if (!handlerReady.has(name)) {
54
+ throw new Error(
55
+ `backgroundTasks.register: '${name}' has no registered iOS launch handler — ` +
56
+ `its defineTask must run at module scope so registration finishes before app launch completes`,
57
+ )
58
+ }
59
+
60
+ BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(identifier)
61
+
62
+ const request = BGAppRefreshTaskRequest.alloc().initWithIdentifier(identifier)
63
+ const interval = registered.get(name)
64
+
65
+ if (interval) {
66
+ request.earliestBeginDate = (globalThis as any).NSDate.dateWithTimeIntervalSinceNow(interval)
67
+ }
68
+
69
+ const errorRef = typeof interop !== 'undefined' ? new interop.Reference() : null
70
+ const submitted = BGTaskScheduler.sharedScheduler.submitTaskRequestError(request, errorRef)
71
+
72
+ if (!submitted) {
73
+ const detail = errorRef?.value?.localizedDescription ?? 'unknown scheduler error'
74
+
75
+ throw new Error(
76
+ `backgroundTasks.register: refresh request for '${name}' was rejected — ${detail}. ` +
77
+ `Confirm ${identifier} is in BGTaskSchedulerPermittedIdentifiers and UIBackgroundModes includes fetch`,
78
+ )
79
+ }
31
80
  }
32
81
 
33
82
  // iOS BGTaskScheduler launch handler — the OS calls the registered handler on
34
- // a background thread; we resolve via the JS executor then mark completion.
83
+ // a background thread; we resolve via the JS executor, report its real outcome
84
+ // then resubmit the request while the task stays registered. Completion and
85
+ // expiration funnel through one flag: whichever reaches the OS first marks the
86
+ // task exactly once, and a late executor result is discarded.
35
87
  function iosHandle(task: any): void {
36
- const identifier: string = task?.identifier ?? ''
37
- const name = identifier.startsWith(TASK_PREFIX)
38
- ? identifier.slice(TASK_PREFIX.length)
39
- : identifier
40
- task.expirationHandler = () => {}
41
- runTask(name).finally(() => {
42
- try {
43
- task.setTaskCompletedWithSuccess(true)
44
- } catch {}
45
- })
88
+ const identifier: string = task?.identifier ?? ''
89
+ const name = identifier.startsWith(TASK_PREFIX)
90
+ ? identifier.slice(TASK_PREFIX.length)
91
+ : identifier
92
+
93
+ let expired = false
94
+ let completed = false
95
+ const complete = (success: boolean) => {
96
+ if (completed) {
97
+ return
98
+ }
99
+
100
+ completed = true
101
+ try {
102
+ task.setTaskCompletedWithSuccess(success)
103
+ } catch {}
104
+
105
+ // Requests are single-shot — this run consumed it. Resubmit while the
106
+ // task stays registered so refresh recurs; a run that ended by
107
+ // expiration still leaves the schedule alive.
108
+ if (registered.has(name)) {
109
+ try {
110
+ iosSubmit(name)
111
+ } catch {}
112
+ }
113
+ }
114
+
115
+ task.expirationHandler = () => {
116
+ expired = true
117
+ // The OS is reclaiming the run. The executor may still be mid-flight —
118
+ // signal it cooperatively and complete now; waiting for it risks the
119
+ // process being terminated with the task never marked finished.
120
+ complete(false)
121
+ }
122
+
123
+ const context: TaskContext = {
124
+ name,
125
+ get expired() {
126
+ return expired
127
+ },
128
+ }
129
+
130
+ runTask(name, context).then(
131
+ (result) => complete(result === 'success'),
132
+ () => complete(false),
133
+ )
46
134
  }
47
135
 
48
136
  /** Background-task scheduler service — see BackgroundTasks for the contract. */
49
137
  export const backgroundTasks: BackgroundTasks = {
50
- supported: isIOS ? typeof BGTaskScheduler !== 'undefined' : true,
51
-
52
- defineTask(name: string, executor: TaskExecutor): void {
53
- executors.set(name, executor)
54
- },
55
-
56
- async register(name: string, options?: { minimumInterval?: number }): Promise<void> {
57
- if (!executors.has(name)) {
58
- throw new Error(
59
- `backgroundTasks.register: '${name}' has no defineTask — declare it at module scope`,
60
- )
61
- }
62
- registered.set(name, options?.minimumInterval ?? 0)
63
- if (isIOS) {
64
- if (typeof BGTaskScheduler === 'undefined') {
65
- throw new Error('unsupported: BGTaskScheduler is not available')
66
- }
67
-
68
- const identifier = TASK_PREFIX + name
69
- BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifierLaunchHandler(
70
- identifier,
71
- null,
72
- iosHandle,
73
- )
74
-
75
- const request = BGAppRefreshTaskRequest.alloc().initWithIdentifier(identifier)
76
- const interval = options?.minimumInterval
77
- if (interval) {
78
- request.earliestBeginDate = (globalThis as any).NSDate.dateWithTimeIntervalSinceNow(
79
- interval,
80
- )
81
- }
82
-
83
- BGTaskScheduler.sharedScheduler.submitTaskRequestError(request, null)
84
- return
85
- }
86
- // Android: WorkManager — the Java side reads the registered map off the
87
- // global so a cold start rebuilds scheduled work from defineTask calls.
88
- const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
89
- if (worker?.schedule) {
90
- worker.schedule(name, options?.minimumInterval ?? 0)
91
- }
92
- },
93
-
94
- async unregister(name: string): Promise<void> {
95
- registered.delete(name)
96
- if (isIOS) {
97
- BGTaskScheduler.sharedScheduler?.cancelTaskRequestWithIdentifier?.(TASK_PREFIX + name)
98
- return
99
- }
100
- const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
101
- worker?.cancel?.(name)
102
- },
103
-
104
- async getStatus(): Promise<TaskStatus> {
105
- if (isIOS) {
106
- if (typeof BGTaskScheduler === 'undefined') {
107
- return 'unavailable'
108
- }
109
-
110
- const status = (globalThis as any).UIApplication?.sharedApplication?.backgroundRefreshStatus
111
- // UIBackgroundRefreshStatus: 0 restricted, 1 denied, 2 available
112
- return status === 0 || status === 1 ? 'restricted' : 'available'
113
- }
114
- return 'available'
115
- },
116
-
117
- async isRegistered(name: string): Promise<boolean> {
118
- return registered.has(name)
119
- },
138
+ supported: isIOS ? typeof BGTaskScheduler !== 'undefined' : true,
139
+
140
+ defineTask(name: string, executor: TaskExecutor): void {
141
+ executors.set(name, executor)
142
+ // iOS: Apple's launch-handler registration. Module scope is already the
143
+ // contract, which is exactly Apple's "before app launch finishes" window.
144
+ // Registration is once per identifier — a second registration of the
145
+ // same identifier kills the app, so a failure is never retried. An
146
+ // "already registered" failure still marks the identifier ready: a module
147
+ // re-eval (hot reload) finds the handler the first evaluation registered.
148
+ if (isIOS && typeof BGTaskScheduler !== 'undefined' && !handledIdentifiers.has(name)) {
149
+ handledIdentifiers.add(name)
150
+ try {
151
+ const registeredHandler =
152
+ BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifierUsingQueueLaunchHandler(
153
+ TASK_PREFIX + name,
154
+ null,
155
+ iosHandle,
156
+ )
157
+
158
+ if (registeredHandler) {
159
+ handlerReady.add(name)
160
+ }
161
+ } catch (error) {
162
+ if (/already been registered/i.test(String(error))) {
163
+ handlerReady.add(name)
164
+ }
165
+ }
166
+ }
167
+ },
168
+
169
+ async register(name: string, options?: { minimumInterval?: number }): Promise<void> {
170
+ if (!executors.has(name)) {
171
+ throw new Error(
172
+ `backgroundTasks.register: '${name}' has no defineTask — declare it at module scope`,
173
+ )
174
+ }
175
+
176
+ if (isIOS) {
177
+ if (typeof BGTaskScheduler === 'undefined') {
178
+ throw new Error('unsupported: BGTaskScheduler is not available')
179
+ }
180
+
181
+ registered.set(name, options?.minimumInterval ?? 0)
182
+ try {
183
+ iosSubmit(name)
184
+ } catch (error) {
185
+ registered.delete(name)
186
+ throw error
187
+ }
188
+
189
+ return
190
+ }
191
+
192
+ // Android: WorkManager — the Java side reads the registered map off the
193
+ // global so a cold start rebuilds scheduled work from defineTask calls.
194
+ // `Utils.android` is a {} stub off Android, so the context stays absent
195
+ // and scheduling is skipped there.
196
+ const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
197
+ const context = (Utils.android as any)?.getApplicationContext?.()
198
+
199
+ if (worker?.schedule && context) {
200
+ worker.schedule(context, name, options?.minimumInterval ?? 0)
201
+ }
202
+
203
+ registered.set(name, options?.minimumInterval ?? 0)
204
+ },
205
+
206
+ async unregister(name: string): Promise<void> {
207
+ registered.delete(name)
208
+ if (isIOS) {
209
+ BGTaskScheduler.sharedScheduler?.cancelTaskRequestWithIdentifier?.(TASK_PREFIX + name)
210
+ return
211
+ }
212
+
213
+ const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
214
+ const context = (Utils.android as any)?.getApplicationContext?.()
215
+
216
+ if (context) {
217
+ worker?.cancel?.(context, name)
218
+ }
219
+ },
220
+
221
+ async getStatus(): Promise<TaskStatus> {
222
+ if (isIOS) {
223
+ if (typeof BGTaskScheduler === 'undefined') {
224
+ return 'unavailable'
225
+ }
226
+
227
+ const status = (globalThis as any).UIApplication?.sharedApplication?.backgroundRefreshStatus
228
+
229
+ // UIBackgroundRefreshStatus: 0 restricted, 1 denied, 2 available
230
+ return status === 0 || status === 1 ? 'restricted' : 'available'
231
+ }
232
+
233
+ return 'available'
234
+ },
235
+
236
+ async isRegistered(name: string): Promise<boolean> {
237
+ return registered.has(name)
238
+ },
120
239
  }
121
240
 
122
- // Worker → JS entry. platforms/android's TaskWorker calls this after bringing
123
- // the runtime up; buffered invocations replay once an executor exists.
124
- ;(globalThis as any).__xplatBackgroundTaskRun = (name: string, done: (r: string) => void) => {
125
- runTask(name).then(
126
- (r) => done(r),
127
- () => done('failed'),
128
- )
241
+ // Worker → JS entry. Android's TaskWorker invokes the TaskRunner registered
242
+ // at module evaluation — calls from the worker thread dispatch onto the JS
243
+ // thread, then the worker blocks on TaskOutcome until the executor settles.
244
+ const taskWorker = (globalThis as any).com?.octanexplat?.tasks?.TaskWorker
245
+
246
+ if (!isIOS && typeof taskWorker?.setTaskRunner === 'function') {
247
+ taskWorker.setTaskRunner(
248
+ new taskWorker.TaskRunner({
249
+ run(name: string, outcome: { onResult(r: string): void }) {
250
+ const report = (r: string) => {
251
+ try {
252
+ outcome.onResult(r)
253
+ } catch {}
254
+ }
255
+
256
+ runTask(name, { name, expired: false }).then(report, () => report('failed'))
257
+ },
258
+ }),
259
+ )
129
260
  }
@@ -6,10 +6,10 @@ const unsupported = () => Promise.reject(new Error('unsupported: no background t
6
6
 
7
7
  /** Background-task scheduler service — see BackgroundTasks for the contract. */
8
8
  export const backgroundTasks: BackgroundTasks = {
9
- supported: false,
10
- defineTask: () => {},
11
- register: unsupported,
12
- unregister: unsupported,
13
- getStatus: async (): Promise<TaskStatus> => 'unavailable',
14
- isRegistered: async () => false,
9
+ supported: false,
10
+ defineTask: () => {},
11
+ register: unsupported,
12
+ unregister: unsupported,
13
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
14
+ isRegistered: async () => false,
15
15
  }
@@ -3,14 +3,14 @@
3
3
  import type { BackgroundTasks, TaskStatus } from './types'
4
4
 
5
5
  const unsupported = () =>
6
- Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
6
+ Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
7
7
 
8
8
  /** Background-task scheduler service — see BackgroundTasks for the contract. */
9
9
  export const backgroundTasks: BackgroundTasks = {
10
- supported: false,
11
- defineTask: () => {},
12
- register: unsupported,
13
- unregister: unsupported,
14
- getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
- isRegistered: async () => false,
10
+ supported: false,
11
+ defineTask: () => {},
12
+ register: unsupported,
13
+ unregister: unsupported,
14
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
+ isRegistered: async () => false,
16
16
  }
package/src/types.ts CHANGED
@@ -4,8 +4,14 @@ export type TaskResult = 'success' | 'failed'
4
4
 
5
5
  /** Invocation payload handed to a TaskExecutor. */
6
6
  export interface TaskContext {
7
- /** The registered task name — one executor may serve several names. */
8
- name: string
7
+ /** The registered task name — one executor may serve several names. */
8
+ name: string
9
+ /** true once the OS has reclaimed the run's time budget (the iOS
10
+ * expiration handler). Cancellation is cooperative: the executor cannot
11
+ * be preempted, so check this between awaits and resolve promptly. The
12
+ * task is already being completed as failed — a late result is
13
+ * discarded. Always false on platforms without an expiration concept. */
14
+ readonly expired: boolean
9
15
  }
10
16
 
11
17
  /** The task body; resolves 'success' | 'failed' for OS scheduling feedback. */
@@ -17,26 +23,35 @@ export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>
17
23
  export type TaskStatus = 'available' | 'restricted' | 'unavailable'
18
24
 
19
25
  /** Background-task façade. Tasks are defined at module scope, then
20
- * registered/unregistered against the OS scheduler (iOS BGTaskScheduler /
26
+ * enabled/disabled against the OS scheduler (iOS BGTaskScheduler /
21
27
  * Android WorkManager-style periodic work). Intervals are minimums — the OS
22
28
  * decides actual timing. */
23
29
  export interface BackgroundTasks {
24
- /** Synchronous fast check — a background-task scheduler exists. */
25
- readonly supported: boolean
26
- /** Define a task at module scope — the OS may invoke the name before any
27
- * other call, so registration must be load-time (expo-task-manager's
28
- * structural constraint, mirrored deliberately). */
29
- defineTask(name: string, executor: TaskExecutor): void
30
- /** Schedule a defined task. `minimumInterval` is a hint in scheduler units
31
- * (seconds on iOS via earliestBeginDate) — the OS decides actual timing
32
- * and may defer well past it. */
33
- register(name: string, options?: { minimumInterval?: number }): Promise<void>
34
- /** Cancel a previously registered task; no-op when not registered. */
35
- unregister(name: string): Promise<void>
36
- /** Current OS scheduling posture for this app. */
37
- getStatus(): Promise<TaskStatus>
38
- /** Whether `name` is currently scheduled with the OS. */
39
- isRegistered(name: string): Promise<boolean>
30
+ /** Synchronous fast check — a background-task scheduler exists. */
31
+ readonly supported: boolean
32
+ /** Define a task at module scope — the OS may invoke the name before any
33
+ * other call, so registration must be load-time (expo-task-manager's
34
+ * structural constraint, mirrored deliberately). On iOS this is also
35
+ * Apple's launch-handler registration, which must finish before app
36
+ * launch completes and is registered once per task for the process'
37
+ * lifetime — module scope is what makes both requirements safe. */
38
+ defineTask(name: string, executor: TaskExecutor): void
39
+ /** Enable or reschedule a defined task by submitting the next refresh
40
+ * request. Idempotent — a repeated call replaces the pending request, so
41
+ * it is safe to call at every launch or from an enable action. iOS
42
+ * requests are single-shot: the scheduler resubmits after each run while
43
+ * the task stays enabled. `minimumInterval` is a hint in scheduler units
44
+ * (seconds on iOS via earliestBeginDate) — the OS decides actual timing
45
+ * and may defer well past it. */
46
+ register(name: string, options?: { minimumInterval?: number }): Promise<void>
47
+ /** Cancel a previously enabled task's pending request; no-op when not
48
+ * enabled. Does not interrupt an executor already running. */
49
+ unregister(name: string): Promise<void>
50
+ /** Current OS scheduling posture for this app. */
51
+ getStatus(): Promise<TaskStatus>
52
+ /** Whether `name` is enabled in this process — an in-memory record, not a
53
+ * query of the OS's durable request queue. */
54
+ isRegistered(name: string): Promise<boolean>
40
55
  }
41
56
 
42
57
  export declare const backgroundTasks: BackgroundTasks
@@ -2,13 +2,7 @@
2
2
  "version": 1,
3
3
  "files": [
4
4
  "background-tasks.d.ts",
5
- "background-tasks.linux.d.ts",
6
- "background-tasks.macos.d.ts",
7
- "background-tasks.web.d.ts",
8
- "background-tasks.windows.d.ts",
9
5
  "index.d.ts",
10
- "index.macos.d.ts",
11
- "index.web.d.ts",
12
6
  "types.d.ts"
13
7
  ]
14
8
  }
@@ -5,6 +5,12 @@ export type TaskResult = 'success' | 'failed';
5
5
  export interface TaskContext {
6
6
  /** The registered task name — one executor may serve several names. */
7
7
  name: string;
8
+ /** true once the OS has reclaimed the run's time budget (the iOS
9
+ * expiration handler). Cancellation is cooperative: the executor cannot
10
+ * be preempted, so check this between awaits and resolve promptly. The
11
+ * task is already being completed as failed — a late result is
12
+ * discarded. Always false on platforms without an expiration concept. */
13
+ readonly expired: boolean;
8
14
  }
9
15
  /** The task body; resolves 'success' | 'failed' for OS scheduling feedback. */
10
16
  export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>;
@@ -13,7 +19,7 @@ export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>;
13
19
  * platform has no background-task path at all. */
14
20
  export type TaskStatus = 'available' | 'restricted' | 'unavailable';
15
21
  /** Background-task façade. Tasks are defined at module scope, then
16
- * registered/unregistered against the OS scheduler (iOS BGTaskScheduler /
22
+ * enabled/disabled against the OS scheduler (iOS BGTaskScheduler /
17
23
  * Android WorkManager-style periodic work). Intervals are minimums — the OS
18
24
  * decides actual timing. */
19
25
  export interface BackgroundTasks {
@@ -21,19 +27,28 @@ export interface BackgroundTasks {
21
27
  readonly supported: boolean;
22
28
  /** Define a task at module scope — the OS may invoke the name before any
23
29
  * other call, so registration must be load-time (expo-task-manager's
24
- * structural constraint, mirrored deliberately). */
30
+ * structural constraint, mirrored deliberately). On iOS this is also
31
+ * Apple's launch-handler registration, which must finish before app
32
+ * launch completes and is registered once per task for the process'
33
+ * lifetime — module scope is what makes both requirements safe. */
25
34
  defineTask(name: string, executor: TaskExecutor): void;
26
- /** Schedule a defined task. `minimumInterval` is a hint in scheduler units
35
+ /** Enable or reschedule a defined task by submitting the next refresh
36
+ * request. Idempotent — a repeated call replaces the pending request, so
37
+ * it is safe to call at every launch or from an enable action. iOS
38
+ * requests are single-shot: the scheduler resubmits after each run while
39
+ * the task stays enabled. `minimumInterval` is a hint in scheduler units
27
40
  * (seconds on iOS via earliestBeginDate) — the OS decides actual timing
28
41
  * and may defer well past it. */
29
42
  register(name: string, options?: {
30
43
  minimumInterval?: number;
31
44
  }): Promise<void>;
32
- /** Cancel a previously registered task; no-op when not registered. */
45
+ /** Cancel a previously enabled task's pending request; no-op when not
46
+ * enabled. Does not interrupt an executor already running. */
33
47
  unregister(name: string): Promise<void>;
34
48
  /** Current OS scheduling posture for this app. */
35
49
  getStatus(): Promise<TaskStatus>;
36
- /** Whether `name` is currently scheduled with the OS. */
50
+ /** Whether `name` is enabled in this process — an in-memory record, not a
51
+ * query of the OS's durable request queue. */
37
52
  isRegistered(name: string): Promise<boolean>;
38
53
  }
39
54
  export declare const backgroundTasks: BackgroundTasks;
@@ -1,3 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- /** Background-task scheduler service — see BackgroundTasks for the contract. */
3
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,3 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- /** Background-task scheduler service — see BackgroundTasks for the contract. */
3
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,3 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- /** Background-task scheduler service — see BackgroundTasks for the contract. */
3
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,3 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- /** Background-task scheduler service — see BackgroundTasks for the contract. */
3
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,2 +0,0 @@
1
- export * from './types.js';
2
- export { backgroundTasks } from './background-tasks.macos.js';
@@ -1,2 +0,0 @@
1
- export * from './types.js';
2
- export { backgroundTasks } from './background-tasks.web.js';